首页 > 解决方案 > ConnectionRefusedError:在为烧瓶应用程序构建 docker 映像时无法连接 MySQL 容器

问题描述

我正在尝试为烧瓶应用程序构建 docker 映像。该应用程序使用另一个 MySQL docker 映像作为依赖项,我收到以下错误日志

Generating a RSA private key
db_1   | ..+++++
db_1   | ..........................................................................+++++
db_1   | unable to write 'random state'
db_1   | writing new private key to 'client-key.pem'
db_1   | -----
db_1   | Certificates initialized
db_1   | MySQL init process in progress...
web_1  | Connecting root@127.0.0.1:3306
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 583, in connect
web_1  |     **kwargs)
web_1  |   File "/usr/local/lib/python3.6/socket.py", line 724, in create_connection
web_1  |     raise err
web_1  |   File "/usr/local/lib/python3.6/socket.py", line 713, in create_connection
web_1  |     sock.connect(sa)
web_1  | ConnectionRefusedError: [Errno 111] Connection refusedweb_1  | Connecting root@127.0.0.1:3306
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 583, in connect

下面是我的 Dockerfile 和 docker-compose.yml

Dockerfile

# this is an official Python runtime, used as the parent image
FROM python:3.6.5-slim

# set the working directory in the container to /app



ADD . /app
WORKDIR /app
RUN pip install -r requirements.txt
# unblock port 80 for the Flask app to run on
WORKDIR /app
ADD . /app/datajoint-python
RUN pip install -e datajoint-python
EXPOSE 1234
CMD ["python", "run.py"]

码头工人-compose.yml

version: '2'
services:
  web:
    build: .
    ports:
      - "1234:1234"
    volumes:
      - .:/app
    depends_on:
      - "db"
    restart: always
  db:
    image: datajoint/mysql
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=simple
      - MYSQL_USER=root
    restart: always

我已经尝试了很多事情,比如在我的应用程序目录中复制 id_rsa 文件。但是,我无法弄清楚为什么会出现错误。我构建并尝试通过执行来运行所有内容

sudo docker-compose up

我在 MacOS 上运行所有这些。任何帮助将不胜感激。

标签: mysqldockerflaskdocker-composedockerfile

解决方案


问题是您的 Web 容器在 MySQL 实例启动并准备好服务请求之前尝试连接到它。depends_on:不足以修复依赖关系。

db_1   | MySQL init process in progress...
web_1  | Connecting root@127.0.0.1:3306
web_1  | Traceback (most recent call last):

您可以通过为您的 Web 应用程序引入等待功能来解决此问题,为此将您的 docker 文件更改为

# this is an official Python runtime, used as the parent image
FROM python:3.6.5-slim

ADD . /app
WORKDIR /app
RUN apt-get update && apt-get install netcat -y
RUN pip install -r requirements.txt
# unblock port 80 for the Flask app to run on
WORKDIR /app
ADD . /app/datajoint-python
RUN pip install -e datajoint-python
EXPOSE 1234
COPY ./docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]

添加 docker-entrypoint.sh (chmod a+x)

#!/bin/sh -e

until nc -vz db:3306 > /dev/null; do
    >&2 echo "db:3306 is unavailable - sleeping"
    sleep 2
  done
  >&2 echo "db:3306 is up"

python run.py

exit 0

推荐阅读