What is Docker?
Wikipedia defines Docker as
an open-source project that automates the deployment of software applications inside containers by providing an additional layer of abstraction and automation of OS-level virtualization on Linux.
- Docker image — a read-only template for an application. Images are stored in a series of read-only layers on the host machine.
- Container — similar to directory; created from Docker images and has everything needed for an application to run
- Docker Daemon (dockerd) — the background service running on the host that manages building, running, and distributing your Docker containers
- Docker Client — the command line tools that allows Docker users to interact with Daemon (e.g. when you run docker run, the client sends this command to dockerd, which carries it out)
- Docker Hub — a registry of Docker images; a cloud service, similar to Github, which allows developers to share applications and automate workflows
Define a container with Dockerfile
The Dockerfile is the build instructions to build the image. The commands you write in a Dockerfile are almost identical to their equivalent Linux commands.
The Dockerfile we are going to use is a file that I have created for the purpose of this demo.
- The first part is the
FROMcommand, which allows us to initialize the build over a base image. Using the
FROM image:lastestis not the best practice for keeping your container up-to-date and secure. In this example, I’m using the python 3.7-slim-buster docker image
RUNcommand executes commands needed to set up your image for the application, such as installing packages, editing files, making directory or changing file permissions.
- I created a work directory called
addwhere the working directory will be set.
- We need to define the port number that needs to be exposed. We’ll indicate the port as
5000since our flask app is running on port
CMDis the command that is executed when you start a container. Here, I‘m using
CMDto run my flask application.
Build you image
Now that you have a Dockerfile, it’s time to build your first image by running the following command. The basic format for using docker command is:
$ docker command [options]
$ docker build -t yourImageName .
Run your image as a container
Run the following command to start a container based on your new image:
$ docker run -p 5000:5000 --rm --name yourContainerName yourImageName
p 5000:5000maps network service port 5000 in the container to 5000 on our host system.
—-rmcauses Docker to automatically remove the container when it exits
--namespecifies a name with which you can refer to your container in subsequent commands
Now you can visit your application in a browser at
0.0.0.0:5000 . When you want to stop the container, hit
Ctrl + C .