Hello friends, I have an error in docker, my server cannot connect to the database. server: nodejs db: mysql
docker file
FROM node:16
WORKDIR /index
COPY package.json .
RUN npm install
EXPOSE 3000
#CMD ["npm", "start"]
CMD /wait-for-it.sh db:3306 -- npm start
COPY . .
docker-compose.yml
version: "3.8"
networks:
app-tier:
driver: bridge
services:
db:
image: mysql
command: --default-authentication-plugin=mysql_native_password
restart: always
expose:
- "3306"
ports:
- "3306:3306"
networks:
- app-tier
environment:
MYSQL_DATABASE: bdprueba
MYSQL_ALLOW_EMPTY_PASSWORD: ok
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: admin
MYSQL_PASSWORD: bdprueba
MYSQL_ROOT_HOST: '%'
backend:
depends_on:
- db
build: .
command: bash -c 'while !</dev/tcp/db/3306; do sleep 1; done; npm start'
ports:
- "3000:3000"
networks:
- app-tier
.env
NODE_ENV=development
DB_HOST=localhost
DB_USER=admin
DB_PASSWORD=dbprueba
DB_NAME=dbprueba
DB_CONNCETION=mysql
PORT=3001
The error is in wanting to use
localhost
as the database host. When using Docker you must use the name of your service to define the connection.In this case instead of using the name of your service
localhost
asDB_HOST
you should, which isdb