Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

파이썬 - Azure App Service에 응용 프로그램 배포하기 전의 환경

지난 글에서 파이썬 웹 앱을,

파이썬 웹 앱을 Azure App Service에 배포하기
; https://www.sysnet.pe.kr/2/0/13830

배포했었는데요, 이게 참 중간에 너무 생략된 단계가 많아서 혼란이 오는 부분이 있습니다. 관련 내용이 문서화로 공개돼 있긴 한데요,

Built-in images
; https://learn.microsoft.com/en-us/troubleshoot/azure/app-service/faqs-app-service-linux#built-in-images

빠른 참조를 위해 필요한 만큼만 정리해 보겠습니다. ^^




우선, 처음 App Service를 만들고 나면 기본적으로 다음의 메시지를 담은 HTML을 호스팅하는 예제가 자리 잡게 됩니다.

Your web app is running and waiting for your content

Your web app is live, but we don’t have your content yet. If you’ve already deployed, it could take up to 5 minutes for your content to show up, so come back soon.

Built with Python

...[생략]...

이 상태에서 SSH 접속을 하게 되면, 초기 시작 디렉터리가 /home/site/wwwroot로 나오고 그 하위에 기본 파이썬 예제 파일들이 있습니다.

/home/site/wwwroot# ls -l
total 4
-rwxrwxrwx 1 nobody nogroup 3269 May 13 05:47 hostingstart.html

얼핏 이 파일이 기본 화면이라고 생각할 수 있지만,

$ cat hostingstart.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Microsoft Azure App Service - Welcome</title>
    <link rel="shortcut icon" href="https://appservice.azureedge.net/images/app-service/v4/favicon.ico" type="image/x-icon" />
    <link href="https://appservice.azureedge.net/css/app-service/v4/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous" />
    <style>
        html, body {
            height: 100%;
            background-color: #ffffff;
            color: #000000;
            font-size: 13px;
        }

        * {
            border-radius: 0 !important;
        }
    </style>
    <script src="https://appservice.azureedge.net/js/app-service/v4/loc.min.js" crossorigin="anonymous"></script>
    <script type="text/javascript">window.onload=function (){try{var a=window.location.hostname; if (a.includes(".azurewebsites.net")){a=a.replace(".azurewebsites.net", "")};var b=document.getElementById("depCenterLink"); b.setAttribute("href", b.getAttribute("href") + "&sitename=" + a); loc()}catch (d){}}</script>
</head>
<body>
    <nav class="navbar"><div class="navbar-brand "><div class="container pl-4 ml-5"><img src="https://appservice.azureedge.net/images/app-service/v4/azurelogo.svg" width="270" height="108" alt="" /></div></div></nav><div class="container-fluid mr-2 mt-5 pt-5"><div class="row"><div class="col-xs-12 col-sm-12 d-block d-lg-none d-xl-none d-md-block d-sm-block d-xs-block"><div class="text-center"><img src="https://appservice.azureedge.net/images/app-service/v4/web.svg" /></div></div><div class="pl-5 ml-5 col-xl-5 col-lg-5 col-md-10 col-sm-11 col-xs-11"><div class="container-fluid"><div class="row"><h2 id="upRunning">Your web app is running and waiting for your content</h2></div><div class="row mt-4 pt-4"><div id="appIsLive" style="font-size:16px;width: 516px;">Your web app is live, but we don’t have your content yet. If you’ve already deployed, it could take up to 5 minutes for your content to show up, so come back soon.</div></div><div class="row mt-4"><h5 class="mt-5"><img src="https://appservice.azureedge.net/images/app-service/v4/code.svg" /><span id="supporting">Supporting Node.js, Java, .NET and more</span></h5></div></div></div><div class="col-xl-5 col-lg-5 col-md-12 d-none d-lg-block"><div class="text-left"><img src="https://appservice.azureedge.net/images/app-service/v4/web.svg" /></div></div><div class="col-xl-1 col-lg-1 col-md-1"></div></div><div class="row mt-4"><div class="container-fluid"><div class="row mt-3"><div class="pl-5 ml-5 col-md-2 mt-4"><p><span id="haventDeployed">Haven’t deployed yet?</span><br /><span id="useDCenter">Use the deployment center to publish code or set up continuous deployment.</span><br /><a id="depCenterLink" href="https://go.microsoft.com/fwlink/?linkid=2057852"><button class="btn btn-primary mt-4" type="submit" id="deplCenter">Deployment center</button></a></p></div><div class="pl-5 ml-5 col-md-2 mt-4"><p><span id="newWebSite">Starting a new web site?</span><br /><span id="followQS">Follow our Quickstart guide to get a web app ready quickly.</span><br /><a href="https://go.microsoft.com/fwlink/?linkid=2084231"><button class="btn btn-primary mt-4" type="submit" id="quickStart">Quickstart</button></a></p></div></div></div></div></div>
</body>
</html>

내용은 같아도 파일 경로는 다릅니다. 첫 페이지가 어딘지 찾기 전에 SSH로 접속한 경우 기본 실행 환경을 구성하는 ~/.bashrc 파일을 살펴볼 필요가 있습니다.

/home/site/wwwroot# cat ~/.bashrc
# ...[주석 생략]...

export PATH="$PATH:/opt/mssql-tools18/bin"
cd /home
alias vizviewer=/opt/startup/code_profiler/vizviewer.sh
export APP_PATH="/home/site/wwwroot"
cd $APP_PATH
export VIRTUALENVIRONMENT_PATH="/home/site/wwwroot/antenv"
. antenv/bin/activate

즉, "cd ..."를 통해 /home/site/wwwroot로 이동하고, 그다음 파이썬 가상 환경인 antenv를 활성화시키는데요, 사실 처음 App Service가 생성된 시점에는 저 디렉터리가 없으므로 SSH 접속 시 저 코드에서 이런 오류 메시지가 나옵니다.

   _____                               
  /  _  \ __________ _________   ____  
 /  /_\  \\___   /  |  \_  __ \_/ __ \ 
/    |    \/    /|  |  /|  | \/\  ___/ 
\____|__  /_____ \____/ |__|    \___  >
        \/      \/                  \/ 
A P P   S E R V I C E   O N   L I N U X

Documentation: http://aka.ms/webapp-linux
Python 3.12.9
Note: Any data outside '/home' is not persisted
-bash: antenv/bin/activate: No such file or directory
root@pywebapp-f00b3990:/home/site/wwwroot# 

그리고 .bashrc의 구성을 이해하려면 Azure App Service 인스턴스가 뜰 때 가장 먼저 실행되는 프로세스를 살펴봐야 하는데요,

# ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.0   2480    68 ?        SNs  06:11   0:00 /bin/sh /opt/startup/startup.sh
root          29  0.0  0.0  13352   420 ?        SNs  06:11   0:00 sshd: /usr/sbin/sshd [listener] 0 of 10-100 startups
root         986  0.0  0.0   6896   172 ?        SN   06:11   0:00 bash /run-diag.sh
root         988  1.1  1.3 3224032 25740 ?       SNl  06:11   0:05 ./DiagServer
root        1011  0.0  0.0   6744  1012 ?        SNs  06:11   0:00 /usr/sbin/cron
root        1023  0.1  1.1 187388 21608 ?        SNl  06:11   0:00 /opt/python/3.12.9/bin/python3 /opt/python/3/bin/gunicorn application:app
root        1026  0.1  1.6 286584 30468 ?        SNl  06:12   0:00 /opt/python/3.12.9/bin/python3 /opt/python/3/bin/gunicorn application:app
root        1029  0.5  1.6 285456 31204 ?        SN   06:12   0:02 /opt/python/3.12.9/bin/python3 /opt/python/3/bin/gunicorn application:app
root        1030  0.5  1.5 285480 30188 ?        SN   06:12   0:03 /opt/python/3.12.9/bin/python3 /opt/python/3/bin/gunicorn application:app
root        1051  0.0  0.1  13464  2992 ?        SNs  06:13   0:00 sshd: root@pts/0
root        1053  0.0  0.1   7160  3384 pts/0    SNs  06:13   0:00 -bash
root        1073  0.0  0.1   9756  3240 pts/0    RN+  06:20   0:00 ps aux

/opt/startup/startup.sh 스크립트의 구성으로 인해,

# cat /opt/startup/startup.sh 
#!/bin/sh

echo 'export APP_PATH="/home/site/wwwroot"' >> ~/.bashrc
echo 'cd $APP_PATH' >> ~/.bashrc

# Enter the source directory to make sure the script runs where the user expects
cd /home/site/wwwroot

export APP_PATH="/home/site/wwwroot"
if [ -z "$HOST" ]; then
                export HOST=0.0.0.0
fi

if [ -z "$PORT" ]; then
                export PORT=80
fi

export PATH="/opt/python//bin:${PATH}"
echo 'export VIRTUALENVIRONMENT_PATH="/home/site/wwwroot/antenv"' >> ~/.bashrc
echo '. antenv/bin/activate' >> ~/.bashrc
  echo WARNING: Could not find virtual environment directory '/home/site/wwwroot/antenv'.
  echo WARNING: Could not find package directory '/home/site/wwwroot/__oryx_packages__'.
GUNICORN_CMD_ARGS="--timeout 600 --access-logfile '-' --error-logfile '-' -c /opt/startup/gunicorn.conf.py --chdir=/opt/defaultsite" gunicorn application:app

~/.bashrc에 있던 내용 중 아래의 분량만큼은,

export APP_PATH="/home/site/wwwroot"
cd $APP_PATH
export VIRTUALENVIRONMENT_PATH="/home/site/wwwroot/antenv"
. antenv/bin/activate

App Service 인스턴스가 생성될 때마다 startup.sh에 의해 언제나 재구성되고 있는 것입니다. (그래서 App Service의 SSH 접속 시마다 .bashrc가 실행돼 /home/site/wwwroot에서 시작하게 되는 것입니다.)




다시 처음 질문으로 돌아가서, 그래서 최초 호스팅되는 페이지의 경로는 /opt/startup/startup.sh 파일의 마지막에 있는 gunicorn 시작 명령어로 알 수 있습니다.

GUNICORN_CMD_ARGS="--timeout 600 --access-logfile '-' --error-logfile '-' -c /opt/startup/gunicorn.conf.py --chdir=/opt/defaultsite" gunicorn application:app


--chdir=/opt/defaultsite 옵션으로 인해 작업 디렉터리가 바뀌는데요, 바로 그 디렉터리에 Azure App Service의 기본 화면을 보여주는 html 파일이 위치하게 됩니다.

# ls /opt/defaultsite/ -l
total 20
-rw-rw-r-- 1 root root  351 Mar  3 07:26 application.py
-rw-rw-r-- 1 root root 3447 Mar  3 07:26 hostingstart_dep.html
-rw-rw-r-- 1 root root 4560 Mar  3 07:26 hostingstart.html
drwxr-xr-x 2 root root 4096 May 13 06:12 __pycache__

그리고 gunicorn이 실행하는 application:app 함수는,

# cat /opt/defaultsite/application.py 
from flask import Flask
import os
app = Flask(__name__, static_folder='/opt/defaultsite')

@app.route('/')
def root():
    if os.path.isdir('/home/site/deployments') and len(next(os.walk('/home/site/deployments'))[1]) > 1:
        return app.send_static_file('hostingstart_dep.html')
    else:
        return app.send_static_file('hostingstart.html')

저렇게 Flask 프레임워크를 초기화하고 hostingstart.html 파일을 '/' 루트 요청의 응답으로 반환하는 역할을 합니다. 이 정도면, 대충 구조가 눈에 들어오시죠? ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/9/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...
NoWriterDateCnt.TitleFile(s)
13217정성태1/13/202313046디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/202312582디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/202316003Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/202315248.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/202312895오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/202314784기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/202314674웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/202313487Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/202312126Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/202313538.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/202214189.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법 [1]파일 다운로드1
13206정성태12/24/202214337.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [4]파일 다운로드1
13205정성태12/24/202212999.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/202212277.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/202212474.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/202214462기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
13201정성태12/20/202215661오류 유형: 835. PyCharm 사용 시 C 드라이브 용량 부족
13200정성태12/19/202213430오류 유형: 834. 이벤트 로그 - SSL Certificate Settings created by an admin process for endpoint
13199정성태12/19/202213561개발 환경 구성: 656. Internal Network 유형의 스위치로 공유한 Hyper-V의 VM과 호스트가 통신이 안 되는 경우
13198정성태12/18/202213858.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
13197정성태12/17/202213332.NET Framework: 2079. .NET Core/5+ 환경에서 XmlSerializer 사용 시 System.IO.FileNotFoundException 예외 발생하는 경우파일 다운로드1
13196정성태12/16/202214121.NET Framework: 2078. .NET Core/5+를 위한 SGen(Microsoft.XmlSerializer.Generator) 사용법
13195정성태12/15/202214344개발 환경 구성: 655. docker - bridge 네트워크 모드에서 컨테이너 간 통신 시 --link 옵션 권장 이유
13194정성태12/14/202214127오류 유형: 833. warning C4747: Calling managed 'DllMain': Managed code may not be run under loader lock파일 다운로드1
13193정성태12/14/202214615오류 유형: 832. error C7681: two-phase name lookup is not supported for C++/CLI or C++/CX; use /Zc:twoPhase-
13192정성태12/13/202214644Linux: 55. 리눅스 - bash shell에서 실수 연산
... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...