Today, i will share you how to create and run Docker-Compose.
First, do you know about Docker-Compose :D.
Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration.
In this application, use the Flask framework and maintain a hit counter in Redis.
* Prerequisites
You need to install:
We don’t need to install Python or Redis. They are provided by Docker Images.
* Basically a three-steps:
– Define the environment with Dockerfile.
– Define the services that make up in docker-compose.yml
– Build and Run, “docker-compose up”
* Let’s start:
– Prepair:
Create a folder to the project
mkdir dockercomposetest
cd dockercomposetest
Create file app.py in your project to hit counter. The default port of redis is 6379.
import time
import redis
from flask import Flask
app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)
def get_hit_count():
retries = 5
while True:
try:
return cache.incr('hits')
except redis.exceptions.ConnectionError as exc:
if retries == 0:
raise exc
retries -= 1
time.sleep(0.5)
@app.route('/')
def hello():
count = get_hit_count()
return 'Hello World! I have been seen {} times.n'.format(count)
– Step 1: To build Docker Image, we need to create dockerfile.
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"]
– Step 2: define services in docker-compose.yml file. We have 2 services are web and redis.
version: '2.0' services: web: build: . ports: - "5000:5000" redis: image: "redis:alpine"
– Step 3: build and run docker-compose.
docker-compose up
Go to the browser, open “http://localhost:5000” . The number will increase when you refresh page.
Done.