How to build and run a Docker Container with Dockerfile

1

A Dockerfile is a text document that contains all the commands we could call on the command line to build a docker image. Using docker build command we can create an automated build that executes several lines of command which are defined in the dockerfile.

In short, docker can build images automatically by reading the instructions from a Dockerfile.

The advantage of using Dockerfile is that we can expect the build of our app defined in the Dockerfile behaves exactly the same wherever it runs.

Step 1: Create a Dockerfile

FIrst. let us create an empty directory on our local machine. Then, change directories (cd) into the new directory, create a file called Dockerfile.

# mkdir myapp
# cd  myapp
# vi Dockerfile

Copy-and-paste the following content into the Dockerfile, and save it.

# Use an official Python runtime as a parent image
FROM python:2.7-slim

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]

This Dockerfile refers to a couple of files we haven’t created yet, namely app.py and requirements.txt. Let’s create those next.

Step 2: Create app.py and requirements.txt

Let us create app.py and requirements.txt in the same folder which contains the Dockerfile.

requirements.txt

Flask
Redis

app.py

from flask import Flask
from redis import Redis, RedisError
import os
import socket

# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)

app = Flask(__name__)

@app.route("/")
def hello():
    try:
        visits = redis.incr("counter")
    except RedisError:
        visits = "<i>cannot connect to Redis, counter disabled</i>"

    html = "<h3>Hello {name}!</h3>" \
           "<b>Hostname:</b> {hostname}<br/>" \
           "<b>Visits:</b> {visits}"
    return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)

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

Step 3: Build the app

We are ready to build the app. Make sure we are still at the top level of our new directory. Here’s what ls should show:

# ls
Dockerfile     app.py   requirements.txt

Now run the build command. This creates a Docker image, which we’re going to name using the --tagoption. Use -t to use the shorter option.

# docker build --tag=myapp .

Next , let us check the build image with below command.

# docker image ls

REPOSITORY         TAG         IMAGE ID
myapp            latest      236754cef254

Step 4: Run the app

We will run the app mapping the machine’s port 8000 to the container’s port 80 using -p:

# docker run -p 8000:80 myapp

We should see a message that Python is serving our app at http://0.0.0.0:80. But that message is coming from inside the container, which doesn’t know we mapped port 80 of that container to 8000, making the correct URL http://localhost:8000

Go to the below URL in a web browser to see the display content served up on a web page.

http://server-ip:8000/

Now let’s run the app in the background, in detached mode:

# docker run -d -p 8000:80 myapp

Our container is now running in the background. We can check the container ID with below command.

# docker container ls
CONTAINER         ID           IMAGE            COMMAND CREATED
1a3f5gh2cs267    myapp     "python app.py"      25 seconds ago

We can also stop and start the conatiner using below command.

Stop the container:

# docker container stop 1a3f5gh2cs267

Start the conatiner:

# docker container start 1a3f5gh2cs267

This completes the Docker build with Dockerfile tutorial. Enjoy your Docker journey!

Please follow and like us:

ZT Admin

One thought on “How to build and run a Docker Container with Dockerfile

  1. Hi,

    Thank you for writing the post. It is very helpful for someone like me who is just starting the Docker journey. Your post is very easy to understand. Please keep posting more post on Docker and Docker Compose.

    Regards,
    Chang

Leave a Reply

Your email address will not be published. Required fields are marked *

Next Post

How to install Percona MySQL 5.7 on CentOS 7

Sat Jul 20 , 2019
The easiest way to install the Percona Yum repository is to install an RPM that configures yum and installs the Percona GPG key. Step 1: Install the Percona repository We can install Percona yum repository by running the following command. # yum install https://repo.percona.com/yum/percona-release-latest.noarch.rpm Retrieving https://repo.percona.com/yum/percona-release-latest.noarch.rpm Preparing... ########################################### [100%] 1:percona-release ########################################### [100%] To install Percona Server with SELinux policies, […]