In this article, we will set up a python Flask application and Dockerize it efficiently in a few minutes.
Steps to Follow
Let’s Create a simple Python Flask Application. Refer to the code here: Docker Flask Repo.
Now, its time to package our application into a docker image. You can create a Dockerfile with the following steps:
1. This installs Python3.7 on the image.
FROM python:3.7
2. Specify DEBIAN_FRONTED=noninteractive
.
ARG DEBIAN_FRONTED=noninteractive
3. Install all the system requirements that are required for the docker image, These are required by the docker container to run the python app
RUN apt-get update && apt-get install -y --no-install-recommends apt-utils > /dev/null
RUN apt-get install -y build-essential tcl
RUN apt-get install -y systemd-sysv
RUN apt-get update > /dev/null
RUN apt-get install -y wget > /dev/null
RUN apt-get install -y zip > /dev/null
RUN apt-get install -y libaio1 > /dev/null
RUN apt-get update > /dev/null
RUN apt-get install -y alien > /dev/null
4. Quicky jump into the working directory where you can copy your code:
WORKDIR /
5. Create a new directory for keeping the Flask application code:
RUN mkdir /code
6. Now change the working directory as shown below:
WORKDIR /code
7. Copy all your workspace files into the image:
COPY . .
8. Now, install all your code dependencies from requirements.txt and upgrade your pip:
pip install -r requirements.txt
RUN pip install --upgrade pip --user
10. Change your working directory where your packaging is done:
WORKDIR /code/k8s
11. Let’s shine the docker instructions from here:
ENTRYPOINT ["make"]
We are done with creating the docker file that is required for a docker image. Now, run the docker file to create an image:
docker build -f ./packaging/flask-docker/Dockerfile . -t flask-docker
Now, let’s create the docker-compose.yml file to run the docker image in a container.
docker_flask
. Run the app.py file with the make
command.version: '3'
services:
flask_web:
image: docker_flask
command: ["run"]
working_dir: /code/flask
ports:
- "5000:5000"
Your make file has does starts your application:
run:
python app.py
From here, start your container which starts your Python Flask web app.
docker-compose up -d
Now your simple Python Flask application is up and running in the Docker container. Now check the container id, with:
docker ps -a
This lists all your docker containers. Check your application logs with:
docker logs -f {container_id}
Now, we are done running the flask web app on a docker container!