我有2个容器,分别是mysql和nodejs。但是,我的nodejs和mysql之间的连接似乎没有连接。错误是
connect ECONNREFUSED 127.0.0.1:8000
我的server.js文件
//Connection with database
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
port: "8000",
user: "root",
password: "root",
database: "justcall"
});
con.connect(function(err){
if(err){
console.log('Database connection error: ' + err.message);
}else{
console.log('Database connection successful');
}
});
我的nodejs的Dockerfile
FROM node:12
RUN useradd -ms /bin/bash admin
WORKDIR /app
COPY . /app
RUN chown -R admin:admin /app
RUN chmod 755 /app
USER admin
CMD npm start
EXPOSE 4443
构建图像
docker build -t nodejs:signalingserver2
我使用以下容器运行容器
docker run -p 4443:4443 nodejs:signalingserver2
我的mysql docker-compose是
version: '3'
services:
mysql:
image: mysql:8.0
container_name: mysql-server-80
# command: --default-authentication-plugin=msql_native_password
# working dir: /application
volumes:
- .:/application
restart: always
ports:
- '3306:3306'
expose:
- '3306'
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=mydb
- MYSQL_USER=root
- MYSQL_PASSWORD=root
phpmyadmin:
depends_on:
- mysql
image: phpmyadmin/phpmyadmin
container_name: phpmyadmin
restart: always
ports:
- "8080:80"
links:
- mysql
environment:
PMA_HOSTS: mysql
php:
container_name: php
image: php:php_img
build:
context: ./
volumes:
- /root/app/xampp/justcall:/var/www/html
ports:
- 8000:80
depends_on:
- mysql
restart: always
问题是每次我运行nodejs服务器时,它都会出现一个错误,该错误是ECONNREFUSED
答案 0 :(得分:0)
您正在尝试连接php-myadmin,而不是MySQL。
尝试将您的连接更改为
//Connection with database
var mysql = require('mysql');
var con = mysql.createConnection({
host: "mysql",
port: "3306",
user: "root",
password: "root",
database: "mydb"
});
此外,将nodejs容器添加到docker-compose或在nodejs容器和MySQL容器之间添加旧版链接。当您使用localhost
时,它指的是节点容器的本地主机,因此您需要使用docker-networking从nodejs容器与数据库容器连接。检查service to service communication。
docker run -it --link mysql -p 4443:4443 nodejs:signalingserver2
此外,取消注释此command: --default-authentication-plugin=msql_native_password
,mysql 8不支持普通身份验证。
使用docker-compose可以
version: '3'
services:
mysql:
image: mysql:8.0
command: --default-authentication-plugin=msql_native_password
ports:
- '3306:3306'
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=mydb
- MYSQL_USER=root
- MYSQL_PASSWORD=root
nodejs:
image: nodejs:signalingserver2
ports:
- '4443:4443'