To understand more about container, lets try to build one. In this post, we will build a hello world application using flask framework.

Before we begin, make sure you already have docker installed by following docker installation guide based on your operating system.

First, lets create folder and make the python code inside it. This simple code is basically our application:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
return "Hello World!"

if __name__ == "__main__":
app.run(host='0.0.0.0')

Next, lets create Dockerfile. Dockerfile is a text file that will contain all instruction/command to build our image.

FROM ubuntu:18.04

RUN apt-get update && apt-get install -y python3 python3-pip
RUN pip3 install Flask

COPY hello.py /app
WORKDIR /app

CMD ["python3", "hello.py"]

This is what our directory looks like now

flask
├── Dockerfile
└── hello.py

Now, lets break line in our Dockerfile and explain it one by one

FROM ubuntu:18.04

This container will use ubuntu 18.04 as it base image. Now, where is this ubuntu:18.04 image is located? First, it will check on your local computer, if its not exist yet, it will then pull the image from docker hub registry by default.

RUN apt-get update && apt-get install -y python3 python3-pip

RUN pip3 install Flask

The first line will install python and python-pip on top of our ubuntu image, and then the second line will install python flask on our image.

COPY hello.py /app

This will copy our script to app folder. If app folder is not exist yet, it will be created

WORKDIR /app

Setting up app folder as our base directory

CMD ["python3", "hello.py"]

Run the command to start flask.

Now, lets build our container image. Run the following command inside the directory

docker build -t helloflask:0.1 .

helloflask:0.1 is the name and tag that we give to our image. Dot in the end of line is current directory, meaning docker build will look for file named Dockerfile in the current directory.

Now we're finished building our image, let's try to run it.

docker run --rm -it -p 80:5000 helloflask:0.1

Lets break down the command used:

  • docker run, this is basically the main command to run container

Now let's open our browser and visit our hello world application.

Our application is up and running

Now, to stop the running container, we can use Ctrl+C on the terminal if we run it interactively. Or we can check its container id by running:

docker ps


CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
34478225c63e helloflask:0.1 "python3 hello.py" 7 minutes ago Up 7 minutes 0.0.0.0:80->5000/tcp sharp_grothendieck

docker stop 34478225c63e

Cloud Engineer