In this blog, I write about Web Development, Blockchain, and DevOps. I am a Docker Captain, Public Speaker, and Developer Advocate at daily.dev. Check my YouTube channel.
Dockerize a Python application - Intro
This article will show how to dockerize a simple Python application.
If you prefer a video version, you can find it here:
version: "3.7": Use the version 3.7 of the Docker Compose file format
services:: The services to run (in this case just one)
mlapp:: The name of the service
container_name: mlapp: The name of the container. It doesn't have to be the same as the service name but it's convenient.
image: francescoxx/mlapp: The name of the image to use. β οΈ replace francescoxx with your dockerhub username or change the name here
ports:: The ports to expose
build:: The instructions to build the image: the context (the current directory) and the Dockerfile to use
πββοΈ Build and run the application
To run the application, you can use the following command:
docker compose up
Note: in case you get an error and you want to run this command again, you can use docker compose up --build to rebuild the image.
If you see something like this, it means that the application is running:
π Test the application
This application is a simple Flask application that returns the sentiment of a text. Let's test if that works with Postman.
We will make 2 simple test with:
positive text π
negative text π
Test 1
Make a POST request to http://localhost:5000/predict with the following body (be sure to have as a header Content-Type: application/json):
{
"text": "May the force be with you"
}
You should get the following response:
Test 2
Make a POST request to http://localhost:5000/predict with the following body (be sure to have as a header Content-Type: application/json):
{
"text": "I hate you"
}
This does work. You can also check the logs of the container to see what's happening:
πΏ Push the image to Docker Hub
Last thing we can do is to push the image on Dockerhub. To do that, you need to create an account on Docker Hub. Then, you can push the image with the following command:
β οΈ replace francescoxx in the docker-compose.yml file with your Docker Hub username!
docker compose push
This will take a while, but after that, you can check your Docker Hub account and you should see the image there:
π Conclusion
In this tutorial, we have seen how to:
create a Docker image for a Python application
run the application with Docker Compose
push the image on Docker Hub.
You can check the 2 videos below for a video version: