无法连接到Mysql docker容器ECONNREFUSED 127.0.0.1:3306

时间:2020-11-09 15:44:02

标签: mysql node.js docker docker-networking

因此,我正在开发一个节点+ mysql后端以自学docker。我已经取得了长足的进步,但是当最终使用npm mysql package连接我的节点实例容器和mysql docker image的容器时,我遇到了一个严重的错误。

 node:events:304
node-server |       throw er; // Unhandled 'error' event
node-server |       ^
node-server | 
node-server | Error: connect ECONNREFUSED 127.0.0.1:3306
node-server |     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1128:16)
                  ...more stack printouts...
node-server |     at emitErrorNT (node:internal/streams/destroy:188:8) {
node-server |   errno: -111,
node-server |   code: 'ECONNREFUSED',
node-server |   syscall: 'connect',
node-server |   address: '127.0.0.1',
node-server |   port: 3306,
node-server |   fatal: true
node-server | }
node-server exited with code 1

我认为这很可能与我的配置有关,但是我对docker compose还是陌生的,所以无论它看起来是否正确,我都不会这样做。那就是为什么我来这里

这是节点服务器的docker文件:

FROM node:alpine

WORKDIR /srv



COPY src/package.json ./
RUN npm install

COPY src/* ./

#intended directory structure
#srv/
#   |package.json
#   |index.js
#


EXPOSE 80

# prevents process from closing prematurely
CMD node index.js && tail -f /dev/null

节点实例中的代码:


const mysql = require('mysql');

// waiting so that the mysql instance has time to initialize before we connect
setTimeout(10000, toCallOnceMySqlIsReady)

function toCallOnceMySqlIsReady(){

  const connection = mysql.createConnection({
    host     : 'database',
    user     : 'node',
    password : 'password',
    database : 'node',
    connectionLimit: 10,
  });

  
  connection.connect();
  
  process.on('exit', function (){
      connection.end();
  });


  module.exports = connection
}

最后是docker-compose.yml:

version: '3'



    # Nov.8 2020 | current problem
    
    # this is past me, I'm here to say that the current problem
    # you were facing was regarding connecting to the mysql database
    #error originate from the 
    #it's probably an error with my docker-compose.yml or Dockerfile 


services:
  database:
    image:
      mysql:latest
    command: --default-authentication-plugin=mysql_native_password
    volumes:
      - ./src/database-service/init:/docker-entrypoint-initdb.d
      - ./src/database-service/database-volume:/var/lib/mysql
    restart:
      always
    environment:
      - MYSQL_DATABASE=node
      - MYSQL_ROOT_PASSWORD=password 
      - MYSQL_USER=node 
      - MYSQL_PASSWORD=password
      - MYSQL_HOST=localhost
    networks:
      - back-end
    ports:
      - 3306:3306
    expose:
      - 3306

    # #for development
    # stdin_open: true # docker run -i
    # tty: true
  server:
    build:
      context: ./src/node-service/
      dockerfile: Dockerfile
    container_name: node-server
    restart: 'no'
    networks:
      - back-end
    ports:
      - "80:80"
    expose:
      - 3306
    
networks:
  back-end:
    driver: bridge

我已经为此工作了几天,所以你们有什么帮助!

0 个答案:

没有答案