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 an empty directory, and create a file named Dockerfile. Filled the file with contents below:
I have made a new directory named app by usemkdir app
andtouch dockerfile
to create a file. Thenvi dockerfile
# Choose a parent image
FROM python:2.7-slim
# Set the working directory of your own
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 launched
CMD ["python", "app.py"]
- Create
requirements.txt
andapp.py
, and keep them in the same folder with theDockerfile
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)
- Build the app
docker build -t friendlyhello
Make sure you are in the top level of your app directory. This command creates a Docker image, tagged with name friendlyhello
To see the local Docker image registry, use
docker image ls
- Run the app
docker run -p 4000:80 friendlyhello
If you want to run app in the background use
docker run -d -p 4000:80 friendlyhello
visit your app
curl http://localhost:4000
- Stop the process
# to see container id
docker container ls
# stop running
docker container stop CONTAINER ID