Compose示例
https://docs.docker.com/compose/gettingstarted/
简单示例
| .
├── Dockerfile
├── app.py
├── docker-compose.yaml
└── requirements.txt
|
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"]
|
app.py
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 | 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)
|
requirements.txt
:
docker-compose.yaml
:
| version: "3.9"
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
|
使用 --env-file 参数
https://docs.docker.com/compose/environment-variables/
docker-compose.yaml
:
| version: "3.9"
services:
redis:
image: "${IMAGE_NAME}"
ports:
- ${PORT}:${PORT}
environment:
- MY_NAME=${MY_NAME}
|
my.env
:
| IMAGE_NAME=redis:alpine
MY_NAME=nocilanro_thx
PORT=6379
|
启动: docker-compose --env-file my.env up -d
查看logs:
| docker-compose --env-file my.env logs
Attaching to test_redis_1
redis_1 | 1:C 13 Jan 2021 03:32:39.394 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1 | 1:C 13 Jan 2021 03:32:39.394 # Redis version=6.0.9, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1 | 1:C 13 Jan 2021 03:32:39.394 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1 | 1:M 13 Jan 2021 03:32:39.396 * Running mode=standalone, port=6379.
redis_1 | 1:M 13 Jan 2021 03:32:39.397 # Server initialized
redis_1 | 1:M 13 Jan 2021 03:32:39.397 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1 | 1:M 13 Jan 2021 03:32:39.398 * Ready to accept connections
|
| ➜ ~ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b372ad687e9b redis:alpine "docker-entrypoint.s…" 2 minutes ago Up 2 minutes 0.0.0.0:6379->6379/tcp test_redis_1
➜ ~ docker exec -ti b372ad687e9b /bin/sh
/data # echo $MY_NAME
nocilanro_thx
|
| from redis import StrictRedis
redis = StrictRedis(host="0.0.0.0", port=6379, db=0)
redis.set('test', "hhh")
print(redis.get('test'))
|
执行脚本输出hhh
关闭: docker-compose --env-file my.env down