연습 - 웹 애플리케이션을 구현하는 코드 작성

완료됨

이 단원에서는 개발자 도구를 사용하여 시작 웹 애플리케이션용 코드를 만듭니다.

새 웹 프로젝트 만들기

.NET CLI 도구의 핵심은 dotnet 명령줄 도구입니다. 이 명령을 사용하여 새 ASP.NET Core 웹 프로젝트를 만듭니다.

다음 명령을 실행하여 “BestBikeApp”이라는 새 ASP.NET Core MVC(Model-View-Controller) 애플리케이션을 만듭니다.

dotnet new mvc --name BestBikeApp

이 명령은 프로젝트를 저장할 "BestBikeApp"이라는 새 폴더를 만듭니다.

선택적으로 웹앱 테스트하기

Azure에서 로컬로 애플리케이션을 테스트할 수 있습니다. 이렇게 하려면 다음 단계를 수행합니다.

  1. 다음 명령을 실행하여 백그라운드에서 웹 애플리케이션을 빌드하고 실행합니다.

    cd BestBikeApp
    dotnet run &
    

    다음 예제와 같은 출력이 표시됩니다.

    [1] <process-number>
    <username> [ ~/BestBikeApp ]$ Building...
    warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
          No XML encryptor configured. Key {b4a2970c-215c-4eb2-92b4-c28d021158c6} may be persisted to storage in unencrypted form.
    info: Microsoft.Hosting.Lifetime[14]
          Now listening on: http://localhost:<port>
    info: Microsoft.Hosting.Lifetime[0]
          Application started. Press Ctrl+C to shut down.
    info: Microsoft.Hosting.Lifetime[0]
          Hosting environment: Development
    info: Microsoft.Hosting.Lifetime[0]
          Content root path: /home/cephas_lin/BestBikeApp
    

    출력에서 <process-number><port> 값을 기록해 둡니다.

  2. 다음 명령을 실행하여 웹 애플리케이션을 탐색하고 <port>를 마지막 단계에서 기록한 포트로 바꿉니다.

    curl -kL http://localhost:<port>/
    

    다음 줄로 끝나는 HTML이 표시됩니다.

    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    </div>
    
            </main>
        </div>
    
        <footer b-b5g3qljvtd class="border-top footer text-muted">
            <div b-b5g3qljvtd class="container">
                &copy; 2024 - BestBikeApp - <a href="/Home/Privacy">Privacy</a>
            </div>
        </footer>
        <script src="/lib/jquery/dist/jquery.min.js"></script>
        <script src="/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="/js/site.js?v=hRQyftXiu1lLX2P9Ly9xa4gHJgLeR1uGN5qegUobtGo"></script>
    
    </body>
    </html>
    
  3. 이전에 기록한 <process-number>를 사용하여 dotnet을 중지합니다.

    kill <process-number>
    

시작 웹 애플리케이션을 만들기 위해 Java 앱에 일반적으로 사용되는 프로젝트 관리 및 빌드 도구인 Maven을 사용합니다. maven-archetype-webapp 템플릿을 사용하여 웹 애플리케이션용 코드를 생성합니다.

  1. 이제 Azure Cloud Shell에서 다음 명령을 실행하여 새 웹앱을 만듭니다.

    cd ~
    mvn archetype:generate -DgroupId=example.demo -DartifactId=helloworld -DinteractiveMode=false -DarchetypeArtifactId=maven-archetype-webapp -DarchetypeVersion=1.5
    
  2. 이제 이러한 명령을 실행하여 새로운 “helloworld” 애플리케이션 디렉터리로 이동하고 배포할 애플리케이션을 패키지합니다.

    cd helloworld
    mvn package
    
  3. 명령 실행이 완료되면 다음 명령을 실행하여 대상 디렉터리를 열고 해당 콘텐츠를 나열합니다.

    cd target
    ls
    

이제 App Service에 배포할 웹 애플리케이션 패키지인 helloworld.war 파일이 있습니다.

시작 Node.js 웹 애플리케이션을 만들려면 노드 패키지 관리자(npm)와 JavaScript 코드를 함께 사용하여 실제 웹 페이지 처리를 실행합니다.

  1. 이제 터미널에서 다음 명령을 실행하여 Node.js 애플리케이션을 설명하는 새로운 package.json 파일을 만듭니다.

    cd ~
    mkdir helloworld
    cd helloworld
    cat >package.json <<EOL
    {
      "name": "helloworld",
      "version": "1.0.0",
      "scripts": {
        "start": "node index.js"
      }
    }
    EOL
    

현재 폴더에 새 package.json 파일이 생성됩니다. 터미널 창에 ls를 입력하면 현재 폴더에서 파일을 찾을 수 있습니다. 웹 사이트 논리를 실행하려면 JavaScript 파일이 필요합니다. 이 기본 예제에서는 하나의 파일 index.js만 있으면 됩니다.

  1. 터미널에서 다음 명령을 실행하여 이 파일을 만듭니다.

    cat >index.js <<EOL
    const http = require('http');
    
    const server = http.createServer(function(request, response) { 
        response.writeHead(200, { "Content-Type": "text/html" });
        response.end("<html><body><h1>Hello World!</h1></body></html>");
    });
    
    const port = process.env.PORT || 1337;
    server.listen(port);
    
    console.log(\`Server running at http://localhost:\${port}\`);
    EOL
    

선택적으로 웹앱 테스트하기

helloworld 웹앱을 실행하는 동안 두 번째 명령 셸 세션을 열어 로컬에서 실행 중인지 확인할 수 있습니다.

  1. 새 브라우저 탭에서 https://shell.azure.com/으로 이동합니다.

  2. 기본 명령 셸 세션에서 다음 명령을 실행하여 백그라운드에서 웹 애플리케이션을 시작합니다.

    cd ~/helloworld
    npm start &
    

    다음 예제와 같은 출력이 표시됩니다.

    [1] <process-number>
    > helloworld@1.0.0 start
    > node index.js
    
    Server running at http://localhost:1337
    

    출력에서 <process-number>의 값을 기록해 둡니다.

  3. 동일한 Cloud Shell 세션에서 다음 명령을 실행하여 웹 애플리케이션을 찾습니다.

    curl -kL http://localhost:1337/
    

    다음과 같은 출력을 얻습니다.

    <html><body><h1>Hello World!</h1></body></html>
    
  4. 이전에 기록한 <process-number>를 사용하여 노드를 중지합니다.

    kill <process-number>
    

시작 웹 애플리케이션을 만들기 위해 웹 애플리케이션 프레임워크인 Flask를 사용합니다.

  1. Azure Cloud Shell에서 다음 명령을 실행하여 가상 환경을 설정하고 프로필에 Flask를 설치합니다.

    python3 -m venv venv
    source venv/bin/activate
    pip install flask
    
  2. 다음 명령을 실행하여 새 웹앱 디렉터리를 만들고 전환합니다.

    mkdir ~/BestBikeApp
    cd ~/BestBikeApp
    
  3. 기본 HTML 응답을 포함하는 application.py라는 새 파일을 만듭니다.

    cat >application.py <<EOL
    from flask import Flask
    app = Flask(__name__)
    
    @app.route("/")
    def hello():
        return "<html><body><h1>Hello Best Bike App!</h1></body></html>\n"
    EOL
    
  4. 애플리케이션을 Azure에 배포하려면 애플리케이션 요구 사항 목록을 requirements.txt 파일에 저장해야 합니다. 이렇게 하려면 다음 명령을 실행합니다.

    pip freeze > requirements.txt
    

선택적으로 웹앱 테스트하기

애플리케이션을 실행하는 동안 Azure에서 로컬로 테스트할 수 있습니다.

  1. 다음 명령을 실행하여 백그라운드에서 웹 애플리케이션을 시작합니다.

    cd ~/BestBikeApp
    export FLASK_APP=application.py
    flask run &
    

    다음 예제와 같은 출력이 표시됩니다.

    [1] <process-number>
     * Serving Flask app 'application.py'
     * Debug mode: off
    WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
     * Running on http://127.0.0.1:5000
    Press CTRL+C to quit
    

    출력에서 <process-number>의 값을 기록해 둡니다. 해당 프로세스가 백그라운드에서 실행 중이므로 CTRL+C로 종료할 수 없습니다. 해당 프로세스 번호를 사용해서 중지시켜야 합니다.

  2. 다음 명령을 실행하여 웹 애플리케이션을 찾습니다.

    curl -kL http://localhost:5000/
    

    다음과 같은 HTML 출력이 표시됩니다.

    <html><body><h1>Hello Best Bike App!</h1></body></html>
    
  3. 이전에 기록한 <process-number>를 사용하여 Flask를 중지합니다.

    kill <process-number>