Docker-compose执行up时报index out of range错误,Flask+Postgres项目启动失败
问题根因
- 直接触发Go运行时panic的原因:
docker-compose.yml中db服务重复声明了volumes字段,你同时配置了命名卷挂载和本地目录挂载两个volumes配置块,早期Docker Compose V2版本对重复配置键的解析逻辑有缺陷,会触发数组索引越界错误。 - 额外配置错误:你使用了命名卷
postgres_data存储Postgres数据,但compose文件最外层没有声明全局volumes字段定义该命名卷,会导致挂载失败。 - 潜在逻辑问题:api服务的启动命令顺序错误,
gunicorn是持久运行的前台进程,写在前面会导致后续flask db upgrade数据库迁移命令永远不会执行;Dockerfile中entry.sh的复制路径错误,会找不到对应文件。
修复步骤
1. 修正docker-compose.yml配置
删除db服务重复的volumes块,二选一保留一种挂载方式,补充缺失的全局命名卷声明(如果使用命名卷的话),修正后的参考配置:
services: api: container_name: api build: context: . dockerfile: api/Dockerfile.api image: mutcompute-api ports: - "5000:5000" volumes: - ./api:/app/ env_file: - ./api/.env command: sh -c "flask db upgrade && gunicorn -b 0.0.0.0:5000 api:app" depends_on: - db client: container_name: client build: context: . dockerfile: client/Dockerfile.client image: mutcompute-client ports: - "3000:3000" volumes: - ./client:/app/ email: container_name: email build: context: . dockerfile: api/Dockerfile.api image: mutcompute-api ports: - "8025:8025" command: python -m smtpd -n -c DebuggingServer 0.0.0.0:8025 db: image: postgres:13-alpine volumes: - ./postgres-data:/var/lib/postgresql/data # 本地绑定挂载,无需额外声明,二选一即可 # - postgres_data:/var/lib/postgresql/data # 命名卷,需要下方全局声明 environment: POSTGRES_USER: mutcompute POSTGRES_PASSWORD: mutcompute POSTGRES_DB: mutcompute_dev ports: - 5405:5432 restart: always # 仅使用命名卷时需要添加以下声明,用本地挂载可删除 # volumes: # postgres_data:
2. 修正Dockerfile配置
修改entry.sh的复制路径,需要时打开执行权限配置:
FROM python:slim LABEL maintainer="Brad Alexander" RUN useradd mutcompute WORKDIR /app COPY . /app/ COPY api/entry.sh /app/ # 修正路径,从api目录下复制文件 ENV FLASK_APP api.py RUN chown -R mutcompute:mutcompute /app && \ chmod +x ./entry.sh && \ # 启用entrypoint时取消注释 pip install -r requirements.txt USER mutcompute EXPOSE 5000
3. 清理缓存重启服务
执行以下命令清理旧的冗余容器缓存,用新配置启动服务:
docker-compose down -v docker-compose up --build
内容的提问来源于stack exchange,提问作者Brad Alexander
相关产品推荐
相关产品推荐

