Before we go
docker-compose
is the only way to setup a multi-containers service.
Here we're trying to setup a simple web service using a backend database redis
. And to make it simpler, we're gonna just use flask
to build a web service.
Environment
- Ubuntu 18.04 (based on Virtualbox 5.10.0)
Code & Scripts
-
app.py
- This is the entry of web service.
import os
import socket
from flask import Flask
from redis import Redis, RedisError
# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)
app = Flask(__name__)
@app.route("/")
def hello():
try:
msg = 'Trying to talk to redis db ...'
visits = redis.incr("counter")
msg += 'It is working.'
except RedisError:
msg += 'cannot connect to Redis, counter disabled'
visits = "<i>cannot connect to Redis, counter disabled</i>"
app.logger.info(msg)
html = "<h3>Hello {name}!</h3>" \
"<b>Hostname:</b> {hostname}<br/>" \
"<b>Visits:</b> {visits}" \
"<b>Error:</b> {msg}"
return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits, msg=msg)
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
-
requirements.txt
- Quick way to install a bunch of Python 3rd-party libs.
flask
redis
-
Dockerfile
- Docker file to build the image.
# Use an official Python runtime as a parent image
FROM python:2.7-slim
# Set the working directory to /app
WORKDIR /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 pypi.python.org -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 5000
# Define environment variable
ENV NAME World
#ENV http_proxy secure-proxy2.qualcomm.com:9090
#ENV https_proxy secure-proxy2.qualcomm.com:9090
# Run app.py when the container launches
CMD ["python", "app.py"]
-
docker-compose.yml
- Docker composer file to setup the service.
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
Get it worked
It's pretty simple, huh? Not until we get it worked.
Run below command in the terminal.
docker-compose up --build
Please always use "--build" in the command, then it'd rebuild the app every time you change it, and start from top, not using any intermediate cache.
Little tips
- Using "logger" instead of "print" to print logs in flask app.
app.logger.info("xxx")
app.logger.error("xxx")
- Another tip is that, always use below command to stop the service. The docker composer will tear down everything for you, hence you're not gonna mess it up.
docker-compose down
OK. Have fun.
网友评论