docker 部署FastApi应用

Docker 2024-01-12 845

项目目录

Docker File

# 引入python版本
FROM python:3.9

RUN mkdir /code
# 设置工作目录
WORKDIR /code

RUN echo '开始构建.............'

# 复制该文件到工作目录中,./requirements.txt表示当前目录下的requirements.txt文件。这里
# 的/code/requirements.txt是docker内部自动生成的工作目录,不用自己创建的,请注意。
COPY ./requirements.txt /code/requirements.txt

# 禁用缓存并批量安装包(后面的链接是利用清华源安装,速度会加快)
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
# 复制代码到工作目录
COPY . /code

# 放开端口
EXPOSE 8001

# 命令行运行,启动uvicorn服务,指定ip和端口(--reload:让服务器在更新代码后重新启动。仅在开发时使用该选项。)
# CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001"]
CMD ["python", "/code/main.py"]

使用以下命令创建镜像

docker build -t mul_admin .

docker-compose.yaml

包含mysql,mongo,redis

version: '3.7'

services:
  app:
#    build: .
    image: mul_admin
    container_name: mul_admin
    restart: always
    ports:
      - "8001:8001"
    volumes:
      - ./app/media:/code/app/media
      - ./app/tasks:/code/app/tasks
      - ./app/logs:/code/app/logs
    environment:
      TZ: "Asia/Shanghai"
    networks:
      custom_network:
  db:
    image: mysql
    container_name: mysql
    command:
      --default-authentication-plugin=mysql_native_password
      --character-set-server=utf8mb4
      --collation-server=utf8mb4_unicode_ci
    restart: always
    ports:
      - "3306:3306"
    volumes:
      - /etc/localtime:/etc/localtime # 设置容器时区与宿主机保持一致
      - /home/docker-images/mysql/my.cnf:/etc/mysql/my.cnf # docker会将cnf文件变为目录 所以需要提前设置cnf文件
      - /home/docker-images/mysql/data:/var/lib/mysql
    environment:
      TZ: Asia/Shanghai
      MYSQL_ROOT_PASSWORD: 
      MYSQL_USER: 
      MYSQL_PASSWORD: 
    networks:
      custom_network:

  redis:
    image: redis
    container_name: redis
    restart: always
    environment:
      TZ: "Asia/Shanghai"
    volumes:
      - /etc/localtime:/etc/localtime
      - /home/docker-images/redis/redis.conf:/usr/local/etc/redis/redis.conf
      - /home/docker-images/redis:/usr/local/etc/redis
    ports:
      - "6379:6379"
    command: ["redis-server","/usr/local/etc/redis/redis.conf"]
    networks:
      custom_network:

  mongo:
    image: mongo
    container_name: mongo
    restart: always
    environment:
      TZ: "Asia/Shanghai"
      MONGO_INITDB_ROOT_USERNAME: 
      MONGO_INITDB_ROOT_PASSWORD: 
    volumes:
      - "/home/docker-images/mongo/data:/data/db"
      - "/home/docker-images/mongo/logs:/var/log/mongodb"
    ports:
      - "27017:27017"
    networks:
      custom_network:
networks:
  custom_network:
    driver: bridge

用到了自定义网络,web应用中的host可以使用容器名称来替换

执行docker-compose up -d 就部署成功

当你web程序中涉及目录的变化,最好将容器停止后,在编译打包部署,否则总是出现各种奇怪的问题

标签:Docker

文章评论

评论列表

已有0条评论