gpt4 book ai didi

docker - 当我尝试将 mysql 与 nodejs 连接时,我的 docker-compose 无法正常工作

转载 作者:行者123 更新时间:2023-12-02 18:52:50 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Docker mysql cant connect to container

(1 个回答)


3年前关闭。




这是我的 db.js 文件

let connection = mysql.createConnection({
host: process.env.DATABASE_HOST || '127.0.0.1',
user: 'root',
database: 'bc2k19',
password: 'joeydash',
port: 33060
});

这是我的 docker-compose.yml 文件
version: '3.2'
services:
app:
build: ./app
ports:
- "3000:3000"
depends_on:
- db
environment:
- DATABASE_HOST=db
db:
build: ./db
ports:
- "3306:3306"

这是我的 mysql dockerfile

FROM mysql:latest

ENV MYSQL_ROOT_PASSWORD joeydash
ENV MYSQL_DATABASE bc2k19
ENV MYSQL_USER joeydash
ENV MYSQL_PASSWORD joeydash

ADD setup.sql /docker-entrypoint-initdb.d

这是我的应用程序的 dockerfile

# Use Node v4 as the base

image.
FROM node:latest

# Add everything in the current directory to our image, in the 'app' folder.
ADD . /app

# Install dependencies
RUN cd /app; \
npm install --production

# Expose our server port.
EXPOSE 3000

# Run our app.
CMD ["node", "/app/bin/www"]

我不知道为什么每次我尝试做 docker-compose up 并连接它时都会显示
     Error: connect ECONNREFUSED 127.0.0.1:3306
app_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)

它就像连接未设置但已设置

最佳答案

这里发生了 3 件事:

  • 您在 nodejs 应用程序 ( db.js ) 中的端口号有错字。
  • 更改 330603306
  • 您的用户是 root然而环境中的用户是joeydash
  • 更改rootjoeydash
  • Mysql 可能会阻止您的连接,因为它默认设置为监听 localhost。容器世界内localhost大多数时候,如果不总是指向容器内。

  • 要解决第二点,您应该检查您的 mysql 配置中的 bind 。部分。 (查找 bind-address )确保它允许来自其他容器正在运行的 ip 的连接。

    • If MySQL binds to 127.0.0.1, then only software on the same computer will be able to connect (because 127.0.0.1 is always the local computer).
    • If MySQL binds to 192.168.0.2 (and the server computer's IP address is 192.168.0.2 and it's on a /24 subnet), then any computers on the same subnet (anything that starts with 192.168.0) will be able to connect.
    • If MySQL binds to 0.0.0.0, then any computer which is able to reach the server computer over the network will be able to connect.


    从这里引用 https://stackoverflow.com/a/3552946/2724940

    如果我们遍历每个场景:
  • 第一个失败,因为所有容器都有自己的 localhost
  • 如果为您的 mysql 配置设置了正确的 ip,则第二个选项可能会起作用。
  • 第三个选项的工作原理是 mysql 现在配置为允许所有远程连接。

  • my.cnf(位于 /etc/mysql/my.cnf
    [mysqld]
    bind-address = 0.0.0.0

    关于docker - 当我尝试将 mysql 与 nodejs 连接时,我的 docker-compose 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53231517/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com