0% found this document useful (0 votes)
52 views

Another - Lab - Get Started With Docker Compose

This document provides instructions for building a simple Python web application using Docker Compose. It contains 4 steps: 1. Setup the application code and dependencies like Flask and Redis. 2. Create a Dockerfile to build an image for the application. 3. Define services for the web and Redis components in a docker-compose.yml file. 4. Run docker-compose up to build the images and start the application containers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Another - Lab - Get Started With Docker Compose

This document provides instructions for building a simple Python web application using Docker Compose. It contains 4 steps: 1. Setup the application code and dependencies like Flask and Redis. 2. Create a Dockerfile to build an image for the application. 3. Define services for the web and Redis components in a docker-compose.yml file. 4. Run docker-compose up to build the images and start the application containers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Get started with Docker Compose

Estimated reading time: 11 minutes

On this page you build a simple Python web application running on Docker Compose. The application uses
the Flask framework and maintains a hit counter in Redis. While the sample uses Python, the concepts
demonstrated here should be understandable even if you’re not familiar with it.

Prerequisites
Make sure you have already installed both Docker Engine and Docker Compose. You don’t need to install
Python or Redis, as both are provided by Docker images.

Step 1: Setup
Define the application dependencies.

1. Create a directory for the project:


2. $ mkdir composetest
3. $ cd composetest

4. Create a file called app.py in your project directory and paste this in:
5. import time
6.
7. import redis
8. from flask import Flask
9.
10. app = Flask(__name__)
11. cache = redis.Redis(host='redis', port=6379)
12.
13. def get_hit_count():
14. retries = 5
15. while True:
16. try:
17. return cache.incr('hits')
18. except redis.exceptions.ConnectionError as exc:
19. if retries == 0:
20. raise exc
21. retries -= 1
22. time.sleep(0.5)
23.
24. @app.route('/')
25. def hello():
26. count = get_hit_count()
27. return 'Hello World! I have been seen {} times.\n'.format(count)

In this example, redis is the hostname of the redis container on the application’s network. We use
the default port for Redis, 6379.
Handling transient errors

Note the way the get_hit_count function is written. This basic retry loop lets us attempt our
request multiple times if the redis service is not available. This is useful at startup while the
application comes online, but also makes our application more resilient if the Redis service needs to
be restarted anytime during the app’s lifetime. In a cluster, this also helps handling momentary
connection drops between nodes.

28. Create another file called requirements.txt in your project directory and paste this in:
29. flask
30. redis

Step 2: Create a Dockerfile


In this step, you write a Dockerfile that builds a Docker image. The image contains all the dependencies the
Python application requires, including Python itself.

In your project directory, create a file named Dockerfile and paste the following:
FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
EXPOSE 5000
COPY . .
CMD ["flask", "run"]

This tells Docker to:

• Build an image starting with the Python 3.7 image.


• Set the working directory to /code.
• Set environment variables used by the flask command.
• Install gcc and other dependencies
• Copy requirements.txt and install the Python dependencies.
• Add metadata to the image to describe that the container is listening on port 5000
• Copy the current directory . in the project to the workdir . in the image.
• Set the default command for the container to flask run.
For more information on how to write Dockerfiles, see the Docker user guide and the Dockerfile reference.

Step 3: Define services in a Compose file


Create a file called docker-compose.yml in your project directory and paste the following:
version: "3.3"
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"

This Compose file defines two services: web and redis.

Web service
The web service uses an image that’s built from the Dockerfile in the current directory. It then binds the
container and the host machine to the exposed port, 5000. This example service uses the default port for the
Flask web server, 5000.

Redis service
The redis service uses a public Redis image pulled from the Docker Hub registry.

Step 4: Build and run your app with Compose


1. From your project directory, start up your application by running docker-compose up.
2. $ docker-compose up -d
3.
4. Creating network "composetest_default" with the default driver
5. Creating composetest_web_1 ...
6. Creating composetest_redis_1 ...
7. Creating composetest_web_1
8. Creating composetest_redis_1 ... done
9. Attaching to composetest_web_1, composetest_redis_1
10. web_1 | * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
11. redis_1 | 1:C 17 Aug 22:11:10.480 # oO0OoO0OoO0Oo Redis is starting
oO0OoO0OoO0Oo
12. redis_1 | 1:C 17 Aug 22:11:10.480 # Redis version=4.0.1, bits=64,
commit=00000000, modified=0, pid=1, just started
13. redis_1 | 1:C 17 Aug 22:11:10.480 # Warning: no config file specified,
using the default config. In order to specify a config file use redis-
server /path/to/redis.conf
14. web_1 | * Restarting with stat
15. redis_1 | 1:M 17 Aug 22:11:10.483 * Running mode=standalone, port=6379.
16. redis_1 | 1:M 17 Aug 22:11:10.483 # WARNING: The TCP backlog setting of
511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the
lower value of 128.
17. web_1 | * Debugger is active!
18. redis_1 | 1:M 17 Aug 22:11:10.483 # Server initialized
19. redis_1 | 1:M 17 Aug 22:11:10.483 # WARNING you have Transparent Huge
Pages (THP) support enabled in your kernel. This will create latency and
memory usage issues with Redis. To fix this issue run the command 'echo
never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to
your /etc/rc.local in order to retain the setting after a reboot. Redis
must be restarted after THP is disabled.
20. web_1 | * Debugger PIN: 330-787-903
21. redis_1 | 1:M 17 Aug 22:11:10.483 * Ready to accept connections

Compose pulls a Redis image, builds an image for your code, and starts the services you defined. In
this case, the code is statically copied into the image at build time.

22. Enter http://localhost:5000/ in a browser to see the application running.

If you’re using Docker natively on Linux, Docker Desktop for Mac, or Docker Desktop for Windows,
then the web app should now be listening on port 5000 on your Docker daemon host. Point your
web browser to http://localhost:5000 to find the Hello World message. If this doesn’t resolve, you
can also try http://127.0.0.1:5000.
If you’re using Docker Machine on a Mac or Windows, use docker-machine ip MACHINE_VM to get
the IP address of your Docker host. Then, open http://MACHINE_VM_IP:5000 in a browser.
You should see a message in your browser saying:
Hello World! I have been seen 1 times.
23. Refresh the page.

The number should increment.


Hello World! I have been seen 2 times.
24. Switch to another terminal window, and type docker image ls to list local images.
Listing images at this point should return redis and web.
$ docker image ls

REPOSITORY TAG IMAGE ID CREATED SIZE


composetest_web latest e2c21aa48cc1 4 minutes ago 93.8MB
python 3.4-alpine 84e6077c7ab6 7 days ago 82.5MB
redis alpine 9d8fa9aa0e5b 3 weeks ago 27.5MB

You can inspect images with docker inspect <tag or id>.


25. Stop the application, either by running docker-compose down from within your project directory in
the second terminal, or by hitting CTRL+C in the original terminal where you started the app.

You might also like