Python, Docker, Compose, Nginx, Flask, Gunicorn 연동하기

Docker 와 Python, Flask 연동 자료가 많이 있기는 하지만 안되는 자료가 많아 최소한으로 작동이 되는 예제를 만들었습니다.

 

 

디렉토리 구조

project/
│
├─ app/
│  ├─ __init__.py
│  ├─ main.py
│  ├─ Dockerfile
│  └─ requirements.txt
│
├─ nginx/
│  ├─ Dockerfile
│  ├─ default.conf
│  └─ nginx.conf
│
└─ docker-compose.yml

 

app/main.py

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello World!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

 

app/Dockerfile

FROM python:latest

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

CMD ["gunicorn", "-b", "0.0.0.0:5000", "--workers", "3", "main:app"]

 

app/requirements.txt

flask
gunicorn

 

nginx/Dockerfile

FROM nginx:stable

COPY default.conf /etc/nginx/conf.d/
COPY nginx.conf /etc/nginx/

 

nginx/nginx.conf

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

 

nginx/default.conf

server {
    listen 80;
    server_name localhost;

    location / {
        proxy_pass http://app:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

 

docker-compose.yml

version: '3.9'

services:
  app:
    build: ./app
    container_name: app
    expose:
      - 5000

  nginx:
    build: ./nginx
    container_name: nginx
    ports:
      - '8011:80'

    depends_on:
      - app

 

명령 (실행 및 중지)

project/ 디렉토리에서 실행

# 실행
$ docker-compose up --build

# 실행(백그라운드 실행)
$ docker-compose up --build -d

# 중지
$ docker-compose down