Docker-compose部署Fastapi、postgres、Redis、Nginx)
之前有写过使用容器部署的方式,这次尝试使用Docker-compose试一次大胆的尝试
使用容器的方式部署只是掌握这项技能的基础,在使用Docker-compose的过程中会有些稍许的不同。毕竟踩过的坑才算是跨过去的坎。具体会使用到Supervisor、Gunicorn、Postgres等
Docker-compose基础文件搭建
- yml文件: 放在项目的根目录下,名字就叫docker-compose.yml
- Dockerfile文件:放在项目的根目录下,文件名字叫Dockerfile,这个文件是项目的Dockerfile文件
- **log文件夹:**放在项目的根目录下,这里会放入日志文件
- **construction文件夹:**在项目中创建这样一个文件夹,里面会放入一些配置文件
这里重点说下construction文件夹,里面放入的东西比较多,我们先从这个文件夹中的配置文件开始说起。在该文件夹中创建五个文件夹:gunicorn、nginx、postgres、redis、superviosr
Construction文件夹的各种文件创建及说明
- **gunicorn:**在该文件夹下创建两个配置文件gunicorn.py、gunicorn.conf
debug = False
daemon = False
bind = '0.0.0.0:8003' # 绑定ip和端口号
backlog = 512 # 监听队列
timeout = 180 # 超时
# worker_class = 'gevent' #使用gevent模式,还可以使用sync 模式,默认的是sync模式
worker_class = 'uvicorn.workers.UvicornWorker'workers = 2 # 进程数
threads = 4 #指定每个进程开启的线程数
loglevel = 'debug' # 日志级别,这个日志级别指的是错误日志的级别,而访问日志的级别无法设置
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' # 设置gunicorn访问日志格式,错误日志无法设置
chdir = '/project'accesslog = "/project/log/gunicorn/success.log" # 访问日志文件
errorlog = "/project/log/gunicorn/error.log" # 错误日志文件
[program:gunicorn] # 这里的gunicorn就是告诉supervisor我们的应用名称叫做什么
process_name=%(program_name)s
command=gunicorn -c /project/construction/gunicorn/gunicorn.py main:app
# 如果上面的命令不起作用,可以使用下面的
# gunicorn main:app --workers 2 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
directory=/project
user=root
autostart=true
autorestart=true
- **nginx文件夹:**在该文件夹下创建Doclerfile文件和conf文件夹,在conf文件夹中创建nginx.conf文件
# nginx镜像
FROM nginx
# 镜像作者
LABEL maintainer="Alfred"
# 换软件源
RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list# 更新依赖
RUN apt-get update -y && \# 安装vim编辑器,方便调试,熟练后可不装apt-get install -y vim && \# 删除原有的配置文件rm /etc/nginx/nginx.conf && \# 创建log文件夹和两个日志文件,这里是为Docker-compose.yml中的数据卷对应mkdir /log && \touch /log/success.log && \touch /log/error.log# 添加配置文件
ADD ./conf/nginx.conf /etc/nginx/nginx.conf
- **postgres文件夹:**这里只需要创建data文件夹
- **redis文件夹:**创建一个conf文件夹里面创建redis.conf,再创建一个data文件夹
bind 0.0.0.0
protected-mode no
port 6379
tcp-backlog 511
timeout 0
tcp-keepalive 300
supervised no
pidfile /var/run/redis_6379.pid
loglevel notice
logfile ""
databases 32
always-show-logo yes
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir ./
replica-serve-stale-data yes
replica-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
replica-priority 100
# 这个是连接密码
requirepass 123456789
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysecno-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64list-max-ziplist-size -2
list-compress-depth 0set-max-intset-entries 512zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
stream-node-max-bytes 4096
stream-node-max-entries 100
activerehashing yesclient-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60hz 10
dynamic-hz yes
aof-rewrite-incremental-fsync yes
rdb-save-incremental-fsync yes
- **supervisor文件夹:**创建supervisord.conf的文件夹
[unix_http_server]
file=/var/run/supervisor.sock ; the path to the socket file[supervisord]
logfile=/project/log/supervisor/supervisor.log ; main log file; default $CWD/supervisord.log
logfile_maxbytes=50MB ; max main logfile bytes b4 rotation; default 50MB
logfile_backups=10 ; # of main logfile backups; 0 means none, default 10
loglevel=info ; log level; default info; others: debug,warn,trace
pidfile=/var/run/supervisord.pid ; supervisord pidfile; default supervisord.pid
nodaemon=false ; start in foreground if true; default false
silent=false ; no logs to stdout if true; default false
minfds=1024 ; min. avail startup file descriptors; default 1024
minprocs=200 ; min. avail process descriptors;default 200
user=root[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface[supervisorctl]
serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL for a unix socket[include]
files=conf.d/*.conf# 配置可视化管理界面,注意一定要先设置端口映射,因为我们在容器中所以port的ip必须为0.0.0.0
[inet_http_server]
port = 0.0.0.0:9010
username = admin
password = 123456789
日志文件夹的创建
在日志文件夹下创建gunicorn和nginx文件夹,并且在两个文件夹下都分别创建success.log、error.log。再创建一个supervisor文件夹,之后在此文件夹中创建superviosr.log文件
根目录下的Dockerfile文件
# 建立 python3.9 环境
FROM python:3.9# 镜像作者
LABEL maintainer="Alfred"RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list# 更新依赖
RUN apt-get -y update && \apt-get -y install vim
# apt-get -y install gcc && \
# apt-get -y install cmake \# RUN apt-get install -y tzdata
# RUN apt-get install -y --fix-missing tzdata# 设置时区
# RUN ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo Asia/Shanghai > /etc/timezone# 设置python环境变量
ENV PYTHONUNBUFFERED 1# 在容器内创建mes文件夹
RUN mkdir -p /peoject# 设置容器内工作目录
WORKDIR /peoject# 将当前目录文件加入到容器工作目录中
ADD . /peoject# 更新pip版本
RUN /usr/local/bin/python -m pip install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple/ && \# pip安装依赖pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/ && \# 安装gunicornpip install gunicorn -i https://pypi.tuna.tsinghua.edu.cn/simple/ && \# 安装supervisorapt-get install -y supervisor && \# 复制supervisor配置文件cp /appagora/construction/supervisor/supervisord.conf /etc/supervisor/supervisord.conf && \# 复制supervisor的gunicorn配置文件cp /appagora/construction/gunicorn/gunicorn.conf /etc/supervisor/conf.d/gunicorn.conf# 设置环境变量
ENV SPIDER=/cyxMES# 移除\r in windows
#RUN sed -i 's/\r//' ./start.sh
#CMD ["supervisord", "-c", "/etc/supervisor/supervisord.conf"]
ENTRYPOINT ["/usr/bin/supervisord", "-n", "-c", "/etc/supervisor/supervisord.conf"]
yml文件
version: "3"
services:redis:image: rediscommand: redis-servervolumes:- ./construction/redis/data:/data # 这里的数据卷与上面创建的文件夹的对应ports:- "6381:6379" # 端口映射restart: always # always表容器运行发生错误时一直重启db:image: postgres:16 # 用16的原因是老版本会有报错environment:- POSTGRES_DB=check# 数据库名称- POSTGRES_USER=baby# 数据库账户- POSTGRES_PASSWORD=baby # 数据库密码volumes:- ./construction/postgres/data:/var/lib/postgres/data # 挂载数据库数据ports:- "5435:5432"restart: alwaysfastapi:build: .expose:- "8003"ports:- "9010:9010" # 这里是端口映射到宿主机对Supervisor进行可视化管理 volumes:- .:/project# 这里的坑我放到下面讲command: >sh -c "[ -e /var/run/supervisor.sock ] && unlink /var/run/supervisor.sock; exec supervisord -n"links:- db- redisdepends_on:- db- redisrestart: alwaysnginx:build: construction/nginxports:- "9000:9000"expose:- "9000"volumes:- ./log/nginx:/log # 挂载日志文件,可以对应一下和上面的创建文件和nginx中的Dockerfile相对应links:- fastapidepends_on:- fastapirestart: always
所有的文件目录结构如下
project/
│
├── construction/
│ ├── gunicorn
│ │ └── gunicorn.conf
│ │ └── gunicorn.py
│
│ ├── nginx
│ │ ├──conf
│ │ │ └──nginx.conf
│ │ └── Dockerfile
│
│ ├── postgres
│ │ ├──data
│
│ │── redis
│ │ ├──data
│ │ ├──conf
│ │ │ └──redis.conf
│
│ │── superviosr
│ │ └── gunicorn.conf
│
│ │── log
│ │ │── gunicorn
│ │ │ └──success.log
│ │ │ └──error.log
│
│ │ │── nginx
│ │ │ └──success.log
│ │ │ └──error.log
│
│ │ │── supervisor
│ │ │ └──supervisor.log
│
│ └── docker-compose.yml
│
│ └──Dockefile