Build my first docker image

Why Docker ?

With docker, it allowed users to create a isolate and independent enviroment to run their code or software.

Using docker, we don’t need to worry about depedencies or compilation. What we need to is launch your container and your application will run immediately.

Docker vs. Virtual Machine ?

Docker is more light than VM.

A VM will include a whole operate system. It work independently and act like a computer.

Docker will only share the resources of the host machine in order to run its enviroments.

So that, Docker is faster and it could launch quickly. And it’s convinent that once the Docker is configured, we don’t need to install other depedency softwares, we could start or stop container quickly and easily.

Start to build a docker container.

In this section, I want to use a simple Flask project to introduce how to create a docker container.

First, we could create a Flask app as below.

Figure 1

And as it shown, when we call flask run, the server binds on our 5000 port and runs smoothly.

Now, if we want to pack our server into a docker container, we need to create a Dockerfile in the root floder. This file is used to config want we want to do in this docker container. Our goal here is to launch a Python script.

1
2
3
4
5
6
7
8
9
10
11
12
13
# A dockerfile must always start by importing the base image.
# We use the keyword 'FROM' to do that.
# `python:latest` is the offical docker image of Python
FROM python:latest

# copy app.py to our image
COPY app.py /

# use pip to install flask dependency
RUN pip install Flask

# define the command we want to run in the image
CMD ["flask", "run"]

After finished editing Dockerfile, we could run the following command to build our container.

-t flag indicate the name of the container and the dot “.” means you use the Dockerfile in the current directory.

1
$ docker build -t docker-flask .

Figure 2

Run the docker image

Once our image was created successfully, we could launch our image.

1
docker run docker-flask

Figure 3

And you could noticed that flask log was output in the terminal, So far, we build a basic docker container.