Linux > Virtualization

How to create a docker file


Dockerfile defines what goes on in the environment inside your container. Access to resources like networking interfaces and disk drives is virtualized inside this environment, which is isolated from the rest of your system, so you need to map ports to the outside world, and be specific about what files you want to “copy in” to that environment.

Create a file called Dockerfile, copy-and-paste the following content into that file, and save it.

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

# Set the working directory to /app

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

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

# Make port 80 available to the world outside this container

# Define environment variable

# Run when the container launches
CMD ["python", ""]
--- End code ---

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

Create two more files, requirements.txt and, and put them in the same folder with the Dockerfile.

Dockerfile is built into an image, and requirements.txt is present because of that Dockerfile’s ADD command, and the output from is accessible over HTTP thanks to the EXPOSE command.


--- Code: ---Flask

--- End code ---

--- Code: ---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__)

def hello():
        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__":'', port=80)

--- End code ---

Build the app

Make sure you are still at the top level of your new directory. Now run the build command. This creates a Docker image, which we’re going to tag using -t so it has a friendly name.

--- Code: ---docker build -t friendlyhello .
--- End code ---

Where is your built image? It’s in your machine’s local Docker image registry:

--- Code: ---$ docker image ls

REPOSITORY            TAG                 IMAGE ID
friendlyhello         latest              326387cea398

--- End code ---

Run the app

--- Code: ---docker run -p 4000:80 friendlyhello
--- End code ---



[0] Message Index

Go to full version