Long time no see. Well, this short post will attempt to fill a small knowledge gap about Docker.
I know that the title might be misleading, but who cares? 🙂
You can just download the code for this post at my Github.
1. Create your code
As shown in the repository, I just created a simple RESTful API with Flask.
The code is pretty straight forward. It simply defines URI routes to certain functions, which return simple strings.
2. Define requirements.txt
Because our code makes use of Flask, we will create a text file containing strings representing the Python (because we wrote the API in python) modules we need to run our code.
3. Create a Dockerfile
In our Dockerfile, we use Docker directives, such as FROM, WORKDIR, RUN, EXPOSE, and CMD to define what the Docker engine should do to create our Docker image.
Dockerfiles should specify everything that is required to run the resulting Docker image. Ours, copies test.py, and the requirements.txt file inside the imagge. Then, it runs pip in order to install the modules into our image.
Furthermore, as in test.py we expose our API through TCP port 5200, we must specify this too for our Docker image.
Then, with CMD we define what is done immediately after the container launches.
4. Create the image following Dockerfile
Assuming Docker is installed on your system, issue the following command to create a Docker image called restapi.
docker build -t restapi .
5. Create a Docker network for your container
It is very likely that you would like to control what IP network your Docker is given. For this to work you need to define a Docker network.
docker network create --subnet=172.18.0.0/16 myDockerNet
The command above creates a subnet, and assigns it the name of myDockerNet
6. Run your image as a Docker container inside myDockerNet
docker run -d --rm -p 5200:5200 --name restapi --net myDockerNet --ip 172.18.0.2 restapi
The command above will run the container as a daemon (-d), will free its name when it is stopped (–rm), any request made to port 5200 will be passed to the container through port 5200 (-p), the container will be called restapi (–name), it will reside in myDockerNet (–net), using IP 172.18.0.2 (–ip).
Pretty simple, isn’t it?
7. Visualize running containers
docker container ls
8. Stop the container
docker stop restapi
This command works because we defined –name when running the image. Otherwise, you should use the name given when visualizing running containers.
Hopefully this silly guide may serve you well.