Monday, November 29, 2021

Run a Python Server in Docker


 


In this post we will review the steps to run a python web server in a docker container.

Let start with a python code to run a simple Hello World server:


server.py

from flask import Flask
from waitress import serve

app = Flask(__name__)


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


serve(app, host="0.0.0.0", port=8080)



To enable our docker image to include all the dependencies, we create a requirements.txt file using the following command:



pip3 freeze > requirements.txt 



Next, let's create the docker file:


Dockerfile

FROM python:3.9.9
WORKDIR /app

COPY src/requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY src /app

CMD [ "python3", "server.py"]



The docker file first installs all the dependencies using the requirements.txt file, and then copies the python source, and runs our web server.




No comments:

Post a Comment