Dockerize a flask application and push to Docker Hub

Dockerize flask application and push to Docker Hub


In this post we will discuss the steps required to create a docker image for a simple flask application.

Once the docker image is created, we will understand the steps required to push the image to Docker Hub.

Project Summary

Let us go through the steps that we will follow.

We will first create a simple flask application. Flask is a web application framework written in Python. It is lightweight and flexible, making it popular for building small to medium-sized web applications.

Next we will create a Dockerfile which will contain steps to create docker image for the flask application. We will create a container from the image to verify that the image works as per our expectation.

Once the image is verified, we will login to and push the image to DockerHub.

Towards the end of the post, we will go through the practices that were followed to create a light weight image that will be consistent across builds.

Step 1: Create Flask Web Application

We will start by creating a new working directory sampleflaskapp.

mkdir sampleflaskapp
cd sampleflaskapp

Now we need to write the application code. For this we will create app.py and requirements.txt files.

The source code discussed in this post can be accessed from https://github.com/thetechdarts/sampleflaskapp

What is app.py file

app.py is a python file in which we will write the main application code. This file will serve as the entrypoint for the flask application.

Step 1.1: Create app.py file

Use your favorite editor to create the file

from flask import Flask
# Create a Flask app instance
app = Flask (__name__)
# Define a route
@app.route("/")
def hello ():
        return "<p style="text-align:center"> Hello, Welcome to flask web app! <p>"
# Run the app if executed directly
if __name__ == '__main__':
        app.run (host = '0.0.0.0')

The route() function of the flask class tells the application which URL should call the function that follows. The function app.run() starts the flask web server and listens for incoming requests on all the network interfaces.

Why is requirements.txt file created?

The file requirements.txt is created to specify the dependencies of the Flask application.

Step 1.2: Create requirements.txt file

We will mention “Flask” along with the version in the file. It suggests that the project relies solely on Flask for its functionality and may not have any additional dependencies. As we have mentioned the flask version, this version will be specifically installed.

Flask==3.0.2

Step 2 : Create Dockerfile

Next we will create a Dockerfile.

What is a docker file?

Dockerfile is a text file that contains the instructions to create a docker image.

Create Dockerfile

We can take the base image to be an OS like Ubuntu or we can take a base image where python has been pre-installed.

FROM python:3.13.0a5-slim-bookworm

Set your working directory

WORKDIR /sampleflaskapp

Copy requirements.txt file to this directory

COPY requirements.txt .

RUN PIP installer. The flag –no-cache-dir directs that there is no need to cache the package being installed locally, since it will not be required by docker container.

RUN pip install –no-cache-dir -r requirements.txt

Copy instruction copies files from the host machine on to the docker image.

COPY . .

Expose the port on which the web server will be listening. Exposing a port is different from publishing a port. Exposing the port makes it clear as to which ports are being used by the app which can later be published when the container is run from the image using docker run command.

EXPOSE 5000

CMD defines what command should be run by default when the container starts. Here we will run the app.py file with the python command.

CMD ["python","app.py"]

Step 3: Build Application Image

Once we have created the required files,
we need to build the docker image. We use -t option to tag the image. As we want to push the image to DockerHub, we need to tag the image with the DockerHub username and repository name. We will use the app name as the repository name.

docker build -t <DockerHub username>/<DockerHub reponame> .

For illustration, we will use username as thetechdarts and repo name as sampleflaskapp to upload the image file to DockerHub. You should replace it with your Docker Hub username and Docker Hub repo name. Hence we will tag the image as follows

docker build -t thetechdarts/sampleflaskapp . 

Verify that the image has been created as with the following command to list the images.

docker images

Step 4: Create docker container

Create a docker container binding port 5000 on the container with port 5000 on host.

docker run -p 5000:5000 <Dockerhubusername>/<DockerHubreponame>

In this step we will verify that the image that we have generated is working as expected. To achieve this, we will need to create a container and access it via ip address of the host machine at port 5000. Once we have verified, we will move on to the next step.

Step 5: Login to Docker Hub

We will need to login to Docker Hub from our terminal to post the image to Docker Hub.

Step 5.1: Pre – requisite

The pre-requisite in this case is to have a user account with DockerHub. If you do not already have an account, you should go to https://hub.docker.com to create a new user account.

Step 5.2: Create Access token

Once a user account is created, you will need an access token.

Screenshot: Generate New Access Token

To create a personal access token in Docker Hub, login to your account in Docker Hub and from the top right select your username avatar, then select My Account from the drop down menu. On the next screen select Security from the left side menu bar. Then select New Access Token on the right side.

You will need to provide the token description by which you will be able to refer to it. Then select access permissions depending on who else will be using this token. Then click Generate to generate the token. Once generated, copy the token and keep it safe with you as it will be displayed only once.

Docker Hub will guide you with the steps on how to use the token from Docker CLI client once you generate the token. We will follow the same steps here to login.

Step 5.3: Login from the terminal

On the docker CLI client, login using docker login command as shown.

docker login – u <username at dockerhub>

You’ll then be prompted for a password

You need to provide the access token generated in the previous step as the password.

Step 6: Push Image to Docker Hub

Once logged in, push the image to Docker Hub as follows.

docker push <DockerHub username>/<DockerHub repo name>

In our case, we will login and push the sample image to the Docker Hub username thetechdarts as follows. You should replace it with your Docker Hub username.

docker push thetechdarts/sampleflaskapp

If we now visit Docker Hub at https://hub.docker.com/repository/docker/thetechdarts/sampleflaskapp, we will be able to see the uploaded image.

Step 7: Run a container with the Docker Hub image

Let us now try fetching the image from Docker Hub and create a docker container. But before that we’ll need to delete the existing image which has been built and pushed to DockerHub as discussed above. If we have the image with us already, the image from Docker Hub will not get downloaded. Also, remove the container so that image can be removed without showing any error.

docker rm <container id>
docker rmi <Dockerhubusername>/<DockerHubreponame>

Once the previous image is removed, we will run the docker container as follows. This will fetch the newly uploaded image and run a container.

docker run -p 5000:5000 <Dockerhubusername>/<DockerHubreponame>

Good practices used for creating docker container

Here we will summarize few good practices that we have used to create a light weight image that is consistent across builds:

Using a slim python image As we already know, that while creating a docker image, we start with an pre-existing image.

Here instead of starting from the OS itself, we are using an image that has python pre-installed. This image is light weight and is optimized to work with basic python related dependencies. So we will have one less layer for creating the docker image.

No cache err flag

We used –no-cache-dir flag when installing flask using pip. This means that we do not want to store the installer in the local system which in this is a docker container. This will keep the container lightweight.

Flask version in requirements.txt

If you have noticed, we have provided a version number for flask in the requirements.txt file. This is to ensure consistency as the same version of flask will be installed each time we will build an image.

Using EXPOSE instruction in Dockerfile

We have chosen to explicitly use EXPOSE instruction in the Dockerfile. This instruction will take the port number as an argument. Please note that the EXPOSE instruction will not bind our port. It is meant to provide information regarding the port on which the application is listening. With this information we know which port should be published while creating a container with docker run command.

Conclusion

In this post we have created a Docker image from a flask web app and pushed to DockerHub.

The source code discussed above can be accessed from https://github.com/thetechdarts/sampleflaskapp

Let me know if you found the post helpful.


Related posts on Docker and Docker Hub:

Simple Jenkins Declarative Pipeline to Push Docker Image To Docker Hub

SonarQube installation on docker container with docker-compose

For more posts on Docker and Docker Hub visit >> here.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *