Node.js able to connect to MySQL container when app is ran locally but unable to connect when app is ran in a container - mysql

Docker-Compose file:
version: '3.8'
networks:
app-tier:
driver: bridge
services:
mysql_node:
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: 'sample_db'
MYSQL_USER: 'user'
MYSQL_PASSWORD: 'password'
MYSQL_ROOT_PASSWORD: 'password'
ports:
- '3306:3306'
expose:
- '3306'
volumes:
- mysql_db:/var/lib/mysql
app:
depends_on:
- mysql_node
build: .
ports:
- 3000:3000
environment:
- MYSQL_HOST=mysql_node
- MYSQL_USER=root
- MYSQL_PASSWORD=password
- MYSQL_NAME=sample_db
- MYSQL_PORT=3306
- MYSQL_HOST_IP=mysql_node
networks:
- app-tier
volumes:
- .:/app
volumes:
mysql_db:
docker file:
FROM node:latest
RUN mkdir app
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 3000
CMD ["node", "app.js"]
Sourcecode:
const http = require('http')
var mysql = require('mysql');
const hostname = '0.0.0.0'
const port = 3000
console.log(process.env.MYSQL_HOST_IP)
console.log(process.env.MYSQL_PORT)
var con = mysql.createConnection({
host: "process.env.MYSQL_HOST_IP",
user: "user",
password: "password",
port: 3306
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
When I run docker-compose up the MySQL container successfully launches. But the app exits, with error code Error: connect ETIMEDOUT.
When I run the app locally via node app.js I end up getting a successful "Connected!" message output to my console.
I'm able to connect to the database via MySQLWorkbench as well. It's just the app is unable to connect to the db when the app is ran as a container.

You've specified that the app should be on a named network and the database shouldn't. Then the database service goes on the default network and the two containers can't talk to each other.
I'd remove the named network from the app, since it's probably not needed.
app:
depends_on:
- mysql_node
build: .
ports:
- 3000:3000
environment:
- MYSQL_HOST=mysql_node
- MYSQL_USER=root
- MYSQL_PASSWORD=password
- MYSQL_NAME=sample_db
- MYSQL_PORT=3306
- MYSQL_HOST_IP=mysql_node
volumes:
- .:/app

Related

trying to connect typeorm to mysql container in docker-compose but got this error Error: Access denied for user ''#'172.29.0.3' (using password: YES)

I am running node and mysql containers with docker compose and try to connect typeorm with mysql container but I got the same error over and over
this my docker-compose file
version: '3.8'
services:
db:
image: mysql
restart: always
ports:
- '3306:3306'
environment:
MYSQL_ROOT_PASSWORD: password
app:
build: .
command: npm start
volumes:
- .:/usr/app/
ports:
- '8000:8000'
depends_on:
- db
environment:
MYSQL_HOST: db
MYSQL_NAME: test
MYSQL_PASSWORD: password
this is my typeorm config file
import {DataSource} from 'typeorm';
import * as dotenv from 'dotenv';
dotenv.config();
export const appDataSource = new DataSource({
type: 'mysql',
host: process.env.MYSQL_HOST,
port: 3306,
password: process.env.MYSQL_PASSWORD,
entities:[
'src/entities/*.js'
],
synchronize: true,
logging: true
});
and this is my .env file
MYSQL_USER = root
MYSQL_PASSWORD = password
MYSQL_NAME = test
MYSQL_HOST = db
MYSQL_PASSWORD = password
Your MySQL and application container seems to be in two different networks.
Try with following docker-compose :
version: '3.8'
services:
db:
image: mysql
restart: always
network_mode: "host"
ports:
- '3306:3306'
environment:
MYSQL_ROOT_PASSWORD: password
app:
build: .
command: npm start
network_mode: "host"
volumes:
- .:/usr/app/
ports:
- '8000:8000'
depends_on:
- db
environment:
MYSQL_HOST: db
MYSQL_NAME: test
MYSQL_PASSWORD: password
here both containers will run on host.
For fixing : > Error: getaddrinfo EAI_AGAIN
Try adding following to /etc/hosts file. (If you are on Linux destro)
0.0.0.0 db
0.0.0.0 app

Error database connect is not a function Nodejs with Mysql in docker

I have deployed my docker application (to DigitalOcean). Everything work's, but I can't connect mysql with nodejs.
When I run docker-compose up I get error database.connect is not a function.
My server.js file is look like this
const mysql = require("mysql");
const database = mysql.createPool({
host: process.env.MYSQL_HOST_IP,
user: "db_user",
password: "db_user_pass",
database: "guess-game",
port: 3306,
});
database.connect((err) => {
if (err) {
console.error("error connecting: " + err.stack);
return;
}
console.log("connected as id " + db.threadId);
});
module.exports = db;
I don't know what I need to write this line to make it work.
host: process.env.MYSQL_HOST_IP,
I tried to add droplet IP as host, but this is also don't work.
host: "http://46.101.162.111/",
Also, I try this.
host: "46.101.162.111",
My docker-compose.yml file
version: "3"
networks:
dbnet:
services:
phpmyadmin:
image: phpmyadmin/phpmyadmin
container_name: phpmyadmin1
environment:
- PMA_ARBITRARY=1
- PMA_HOST=db
restart: always
links:
- db
ports:
- 8899:80
depends_on:
- db
networks:
- dbnet
api:
build: ./api
container_name: api1
command: npm run start
restart: unless-stopped
ports:
- "3005:3005"
environment:
- PORT=3005
- MYSQL_HOST_IP=172.18.0.2
depends_on:
- phpmyadmin
networks:
- dbnet
db:
image: mysql:latest
container_name: db
command: --default-authentication-plugin=mysql_native_password
environment:
- MYSQL_ROOT_PASSWORD=my_secret_password
- MYSQL_DATABASE=guess-game
- MYSQL_USER=db_user
- MYSQL_PASSWORD=db_user_pass
restart: always
ports:
- 6033:3306
networks:
- dbnet
Struggling almost 3 days. 😣
You just need to indicate a DB container name instead of IP like this:
MYSQL_HOST_IP=db

Mysql connection refused in docker-compose

I have a problem connecting to MySQL from my golang app in docker-compose. I can connect to db from console: mysql -u user -D data -h 0.0.0.0 -P3306 -p
But, I can't connect when using docker-compose.
My docker-compose.yml
version: '3'
services:
app:
build: ./
volumes:
- ./internal/app:/app
- ./logs:/var/log/parser
links:
- db
db:
image: mysql:8
container_name: mysqldb
ports:
- "3306:3306"
volumes:
- ./docker/mysql/conf:/etc/mysql/conf/conf.d
- ./docker/mysql/logs/:/var/log/mysql
- ./docker/mysql/init:/docker-entrypoint-initdb.d
- ./docker/mysql/data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: pass
MYSQL_DATABASE: data
MYSQL_USER: user
MYSQL_PASSWORD: pass
In my app main.go
dbConfig := mysql.NewConfig()
dbConfig.User = "user"
dbConfig.Passwd = "pass"
dbConfig.Addr = "mysqldb"
dbConfig.DBName = "data"
dbConfig.Net = "tcp"
db, err := sql.Open("mysql", dbConfig.FormatDSN())
if err != nil {
panic(err.Error())
}
defer db.Close()
But I get this error:
panic: dial tcp 172.20.0.2:3306: connect: connection refused
I think your golang service starts before the MySQL service. so you have to start MySQL service first then golang service so, use depends_on to achieve that.
new docker-compose.yml with depends_on
version: '3'
services:
app:
build: ./
volumes:
- ./internal/app:/app
- ./logs:/var/log/parser
depends_on:
- mysqldb
links:
- db
db:
image: mysql:8
container_name: mysqldb
ports:
- "3306:3306"
volumes:
- ./docker/mysql/conf:/etc/mysql/conf/conf.d
- ./docker/mysql/logs/:/var/log/mysql
- ./docker/mysql/init:/docker-entrypoint-initdb.d
- ./docker/mysql/data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: pass
MYSQL_DATABASE: data
MYSQL_USER: user
MYSQL_PASSWORD: pass

Docker(docker-compose) node + MySQL: ECONNREFUSED

I have a docker-compose.yml file, that is running three containers. My problem is when I start my containers it seems like my node(api) container is starting before my MySQL container, even if I declare depends_on on my docker-compose.yml, giving me the following error:
error connecting: Error: connect ECONNREFUSED xxx.xx.x.x:3306
at TCPConnectWrap.afterConnect [as oncomplete]
After I got this error I can see in my console that the MySQL container is just starting. My database is ok, I can access it without any problems. If I make some change in my nodejs code, then this will make my node server to refresh and when the server is up again I don't have any connections problems, because the MySQL container is already up.
I even tried to use solutions as wait-for-it.sh (https://github.com/vishnubob/wait-for-it/blob/master/wait-for-it.sh), but the result was the same, my node backend tries to make a mysql connection, but the mysql container is not ready.
This is my docker-compose.yml
version: "3"
services:
mysql:
image: my_mysql
build: ./db
restart: always
container_name: my_mysql
volumes:
- /var/lib/mysql
- ./db:/db
ports:
- "3307:3306"
environment:
- MYSQL_ROOT_PASSWORD=x
- MYSQL_USER=x
- MYSQL_PASSWORD=x
- MYSQL_DATABASE=x
networks:
- my_network
command: --default-authentication-plugin=mysql_native_password
api:
container_name: my_api
build: ./api
restart: always
ports:
- "9000:9000"
environment:
DB_HOSTNAME: mysql
working_dir: /api
volumes:
- ./api:/api
depends_on:
- mysql
networks:
- my_network
client:
container_name: my_client
image: mhart/alpine-node:12
build: ./client
restart: always
ports:
- "3000:3000"
working_dir: /client
volumes:
- ./client:/client
entrypoint: ["npm", "start"]
depends_on:
- api
networks:
- my_network
networks:
my_network:
driver: bridge
Dockerfile for my nodejs backend:
FROM mhart/alpine-node:12
WORKDIR /api
COPY package*.json /api/
RUN npm i -G nodemon
RUN npm install
COPY . /api/
EXPOSE 9000
CMD ["npm", "run", "dev"]
Dockerfile for my react front:
FROM mhart/alpine-node:12
WORKDIR /client
COPY package*.json /client/
RUN npm install
COPY . /client/
EXPOSE 3000
CMD ["npm", "start"]
and Dockerfile for mysql:
FROM mysql:8.0.19
Calling mysql connection in nodejs:
const config = require('config');
const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const connection = mysql.createConnection({
host : config.get('mysql.config.host'),
user : config.get('mysql.config.user'),
password : config.get('mysql.config.password'),
database : config.get('mysql.config.database'),
port : config.get('mysql.config.port')
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
router.get("/", function(req, res, next) {
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) {
throw error;
}
res.send(`MySQL OK: ${results[0].solution}`);
});
});
module.exports = router;
Thanks for any help.
I could not test it, but the docker recommendation is to create a script to wait until the other container accepts connections.
Alternatively, write your own wrapper script to perform a more application-specific health check. For example, you might want to wait until Postgres is definitely ready to accept commands:
#!/bin/sh
# wait-for-postgres.sh
set -e
host="$1"
shift
cmd="$#"
until PGPASSWORD=$POSTGRES_PASSWORD psql -h "$host" -U "postgres" -c '\q'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - executing command"
exec $cmd
You could check the documentation here:
Control startup and shutdown order in Compose
Hope this helps.

TCPConnectWrap.afterConnect - node can't get data from mysql when are in docker compose

I'm trying to connect node with mysql through dokcer-compose. I can access mysql with workbench but when I try to connect with node I get the error:
Error: connect ECONNREFUSED 127.0.0.1:3306
     at TCPConnectWrap.afterConnect [as oncomplete] (net.js: 1054: 14))
Does anyone know what is going on?
docker-compose.yml
version: '3'
services:
#App Service
app:
image: "node:alpine"
container_name: cms-node
restart: unless-stopped
tty: true
working_dir: /app
environment:
- NODE_ENV=production
ports:
- 1234:1234
volumes:
- ./:/app
links:
- db
depends_on:
- db
#Mysql Service
db:
image: mysql:latest
container_name: cms-mysql
restart: unless-stopped
# command: --default-authentication-plugin=mysql_native_password
environment:
MYSQL_DATABASE: CMS
MYSQL_USER: root
MYSQL_PASSWORD: root
MYSQL_ROOT_PASSWORD: root
ports:
- 3306:3306
node create connection
const db: Connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'CMS',
});
export default db;
node try to connect
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected!');
});
You should use the link name (by default, the name of the linked service) as the hostname to connect to. See the docker-compose.yml documentation for details.
So just use host: 'db' instead of host: 'localhost'
Yes, we have to use service name from docker-compose.yml. I faced a similar issue when there was a custom front end API Gateway server (working as proxy) written in node.js connecting to other two services. So replacing localhost:3001 with serviceName:30001 fixed the issue.
Example code:
...
const proxy = require('express-http-proxy');
...
app.use('/json-parser', proxy('json_parsing_api:3001'));
app.get('/json-parser/json-to-person', proxy('json-to-person'));