본문으로 건너뛰기

Docker로 작성한 Flask 서버, Debug모드 적용하기

💡 Docker로 올린 서버는 Debug모드로 실행 한다면, Docker 내부에 들어가서 코드를 고쳐줘야 하는 번거로움이 있다. Docker 내부에서 수정한 파일은, Docker를 내리거나 지우면 없어지며 혹은 local의 git과 연동되지 않는 문제점이 있다.

💡 When running a server deployed with Docker in debug mode, there's the inconvenience of having to enter the Docker container to modify the code. Files modified inside Docker are lost when the container is stopped or removed, and there's also the issue of changes not being synced with local git.

  • 간단하게 Dockerfile로, flask 서버를 작성 해 보도록 하겠습니다.

Flask 서버 만들기

여러번 다루었지만, Flask 서버를 시작하기 위해서 가상환경과 필요 패키지들을 설치 해 주도로 하겠다.

Applying Debug Mode to a Server with Docker

  • Let's write a simple Flask server using a Dockerfile.

Creating a Flask Server

As we've covered many times before, let's set up the virtual environment and install the necessary packages to start the Flask server.

.env

FLASK_ENV=development
FLASK_DEBUG=True
FLASK_APP=app.py
FLASK_RUN_PORT=5000

app.py

from flask import Flask

app = Flask(__name__)

@app.route('/',methods=['GET'])
def index():
return "hi!"

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

Dockerfile

FROM python:3

ADD . /www
WORKDIR /www

RUN python3 -m pip install -U pip
RUN pip3 install flask
RUN pip3 install python-dotenv

CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0"]

Docker Run & Build

$ docker build  -t flask_dev -f Dockerfile . && docker run -p 5000:5000 flask_dev

도커파일이 만들어지고 실행이 되었으니 서버로 동작 합니다!

그런데 우리가 작성한 flask 코드를 아무리 수정해도 docker 파일이 수정되지 않습니다.

Docker file에 옵션을 주자

두가지 방법이 있다. Docker Run 옵션을 주는 것과 docker-compose.yml 을 수정 해 주는 것이다.

1번 방법 - Dockerfile Run Command 수정하기

The Dockerfile has been created and executed, so the server is now running!

However, no matter how much you modify the Flask code you wrote, the changes won't be reflected in the Docker container.

Let's Add Options to the Docker File

There are two methods: adding options to the Docker Run command, and modifying the docker-compose.yml file.

Method 1 - Modifying the Dockerfile Run Command

$ docker build  -t flask_dev -f Dockerfile . && docker run -p 5000:5000 --volume=$(pwd):/www flask_dev

2번 방법 - docker-compose.yml을 사용해보기

Method 2 - Using docker-compose.yml

version: '3'

services:
flask_dev:
build:
context: .
dockerfile: Dockerfile
env_file:
- .env
ports:
- 5000:5000
volumes:
- ./:/www
$ docker-compose up --build

이제 소스파일을 수정하면, Docker에 올라간 서버가 수정 될 때 마다 reload 되는 것을 볼 수 있다.

간단하게 작성 하기 위해서 flask서버를 사용했지만, flask외에 Django, Spring, node 등 많은 곳에 적용 할 수 있다.

Now when you modify the source files, you can see the server deployed on Docker reload every time changes are made.

For simplicity, we used a Flask server, but this can be applied to many other frameworks besides Flask, such as Django, Spring, Node, and more.