我的设置是:
我的问题:
我无法将Node.js应用程序连接到数据库。我可以通过dbeaver或命令行在本地访问数据库,因此我知道它正在工作。但是当我尝试在我的index.js上访问它时,出现以下错误:
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
From event:
at _registerHandshakeCmd (/usr/src/app/node_modules/mariadb/lib/connection.js:689:11)
at /usr/src/app/node_modules/mariadb/lib/connection.js:57:11
at new Promise (<anonymous>)
at Connection.connect (/usr/src/app/node_modules/mariadb/lib/connection.js:56:16)
at Object.createConnection (/usr/src/app/node_modules/mariadb/promise.js:17:36)
at Object.<anonymous> (/usr/src/app/src/index.js:24:28)
at Module._compile (internal/modules/cjs/loader.js:1147:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
at Module.load (internal/modules/cjs/loader.js:996:32)
at Function.Module._load (internal/modules/cjs/loader.js:896:14) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
NodeJs Dockerfile:
FROM node:latest
WORKDIR /usr/src/app
COPY package*.json /usr/usr/app
RUN npm install
COPY . /usr/src/app
EXPOSE 8080
CMD ["npm", "start"]
Mariadb Dockerfile:
FROM mariadb:latest
ENV MYSQL_ROOT_PASSWORD=mdp
ENV MYSQL_DATABASE=dashboard
ENV MYSQL_USER=monty
ENV MYSQL_PASSWORD=monty
USER 1000
EXPOSE 3306
docker-compose.yml:
version: '3'
services:
web:
build: ./backend
ports:
- "8080:8080"
volumes:
- ./backend:/usr/src/app/
working_dir: /usr/src/app
environment:
- MARIADB_HOST=database
- MARIADB_PORT_NUMBER=3306
- MARIADB_USER=monty
- MARIADB_PASSWORD=monty
- MARIADB_DATABASE=dashboard
user: "1000"
container_name: backend
depends_on:
- database
links:
- database:database
database:
build: ./database
ports:
- "3306:3306"
expose:
- "3306"
volumes:
- /database/data:/var/lib/mysql:rw
user: "1000"
hostname: "localhost"
environment:
- ALLOW_EMPTY_PASSWORD=yes
- MARIADB_DATABASE=dashboard
- MARIADB_PORT=3306
- MARIADB_USER=monty
- MARIADB_PASSWORD=monty
container_name: database
这是我的index.js:
const express = require('express')
const mariadb = require('mariadb');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(
bodyParser.urlencoded({
extended: true
})
)
app.use(cors());
app.get('/', (req, res) => {
res.send('hello world');
});
const connection = mariadb.createConnection({
host: '127.0.0.1',
user: 'someuser',
password: 'somepassword',
database: 'dashboard',
port: '3306',
}).then(conn => {
console.log('connection established.');
}).catch(err => {
console.log(err);
});
app.listen(8080);
如果有人对您应该看的地方或错误的出处有任何建议,请多谢。谢谢!
答案 0 :(得分:2)
您正在使用127.0.0.1
作为NodeJS应用程序中的数据库主机名。但这是您的NodeJS容器的IP地址。每个容器都有其自己的IP地址(例外:使用docker network host
)。这会导致错误:
Error: connect ECONNREFUSED 127.0.0.1:3306
使用docker-compose
时,可以使用在docker-compose.yml文件中指定的服务名称访问数据库。在您的示例中,服务名称database
可以用作主机名。试试这个:
const connection = mariadb.createConnection({
host: 'database',
...