我有一个 docker compose 文件,如下所示:
version: "3.9" services: mysqldb: image: mysql:5.7 container_name: mysqlcontainer command: --default-authentication-plugin=mysql_native_password volumes: - ./db/init.sql:/docker-entrypoint-initdb.d/0_init.sql ports: - 3306:3306 expose: - 3306 environment: MYSQL_DATABASE: "todos" MYSQL_USER: "admin" MYSQL_PASSWORD: "password" MYSQL_ROOT_PASSWORD: "password" SERVICE_TAGS: dev SERVICE_NAME: mysqldb restart: on-failure networks: - internalnet expressapp: container_name: api build: . image: expressapp:1.0 ports: - "3001:3001" expose: - "3001" environment: DB_HOST: mysqldb DB_PORT: 3306 DB_USER: "admin" DB_PASSWORD: "password" DB_NAME: todos DB_CONNECTION_LIMIT: 20 SERVICE_TAGS: dev SERVICE_NAME: expressapp PORT: 3001 depends_on: - mysqldb networks: - internalnet networks: internalnet: driver: bridge volumes: database:
如果我使用 docker compose up -d
命令启动容器并使用 ps
命令检查正在运行的容器,我将得到以下输出:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 9f338b733a1c expressapp:1.0 "docker-entrypoint.s…" 2 minutes ago Up 2 minutes 0.0.0.0:3001->3001/tcp api edef8027dc0a mysql:5.7 "docker-entrypoint.s…" 2 minutes ago Up 2 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp mysqlcontainer
但是当我尝试向服务器发出 API
请求时,我收到以下错误消息:
"There was an error processing your request: connect ECONNREFUSED 172.24.0.2:3306"
为什么是因为我将 DB_HOST
变量设置为 mysql
服务名称?
This problem may occur because
expressapp
is started beforemysql
is available for queries.To control the service startup order, you can add
healthcheck
to themysqldb
service:and
depends_on
block toexpressapp
View full examplehere
For more information on this, see this answer.