Docker cheatsheet - Create an image from a Dockerfile

Create an image from a Dockerfile

create a folder

$ mkdir myimage

create a file named Dockerfile

$ touch Dockerfile
$ cat Dockerfile
# based on Python
FROM python:2.7-slim

# set the workplace to /app
WORKDIR /app

# copy all the file in current folder to /app directory
COPY . /app

# install the packaged specified by requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

# the port is 80
EXPOSE 80

# environment variable
ENV NAME World

# run app.py file when the docker start
CMD ["python", "app.py"]

In the folder myimage,create two file requirements.txt,app.py

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)

Create an image from the Dockerfile

$ ls
Dockerfile app.py requirements.txt

$ docker build --tag=myhelloapp .

## show the images
$ docker image ls
REPOSITORY            TAG                 IMAGE ID
myhelloapp         latest              326387cea398

Run the app in a new container

$docker run -p 4000:80 myhelloapp

use your browser to open the url http://yourhost_ip:4000

Date: From:www.lautturi.com, cheatsheet