Hello and welcome to the second entry of my tech blog.
Now that we have built a simple API app, we need a place to run it and expose it to our users.
But first things first; in order to build a Docker container we first need a Dockerfile. Since we are deploying just a simple Flask application without any dependencies (such as database) this example is fairly simple. You can see the full Dockerfile below:

We utilise the latest Python version (as of writing this blog post on 22nd of December 2024), expose port 5000 (default for Flask), establish a working directory, install Flask, copy the content of our application there and specify command to run the app. All of it in just 6 lines of code, pretty neat, right?
Dockerfile alone is not enough, we need to build a container image out if it and upload it to container registry. For this I am using Docker Hub public repo.
In order to build an image, navigate to the folder containing Dockerfile and run following command:
docker buildx build -t imagename:version .
By using -t argument we specify a name of the image and version tag. The dot at the end means context of current directory. After execution you should see output similar to the one below (note it might take few minutes to build the image including pulling the python 3.12 base if it’s not in your cache):

Once the image is built, we can run the container instance based on it. To do so, execute the following command:
docker run imagename:version -p 5005:5000
Since our container instance is run locally we’ve utilised port forwarding and we redirect traffic from port 5005 on our local machine to port 5000 in the container instance. Now that container is created let’s make sure it is running. To do so run:
docker container list
Afterwards you should see output similar to the one below (name of the container is generated randomly). The important thing is the „STATUS” section, it should be showing „Up” (not „Exited” or „Created”).

Let’s query our /character endpoint to make sure that the app is indeed running. You can do it by running curl:
curl http://127.0.0.1:5005/character
You should receive the following output in the terminal:

Right now image is present only on our local machine. In order to use it in Azure we first need to push it to Docker Hub registry. To do so first make sure you are logged in Docker by running:
docker login
After that is done you can push the image to registry utilising this command:
docker push imagename:version
It might take a minute or two, during the process you should see output such as:

Last thing to check is the actual Docker Hub registry. Login to hub.docker.com, navigate to repositories section and you should fine your repo containing the image there. In my case it looks the following:

Here it is! Now we have our image in Docker repository ready to be used in a deployment process, which I will cover in the next blog post.
Dodaj komentarz