Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't connect nodejs and mysql in same docker

I'm new in docker and i'm trying to make my nodejs express run inside it. I'm trying to install the dependencies using shellscript and its working but in the end I can't connect to mysql.

My docker file install mysql, create an user and a database, and install nodejs too. Then it runs npm install and try to start my app but knex says it can't connect to the mysql with the message:

Knex:Error Pool2 - Error: connect ECONNREFUSED /var/run/mysqld/mysqld.sock

Here's a gist with the code i'm using. (nodejs part is incomplete, just with the important part):

https://gist.github.com/jradesenv/527f6e59ab2e7985c38fbed3a2084c83

I hope anyone will have a good ideia on how to resolve or debbug this.

like image 439
Jean Robert Avatar asked Feb 06 '23 19:02

Jean Robert


2 Answers

The best practice is to keep the components of a micro-service separate in their own container.

See for instance "Learn Docker by building a Microservice" from Dave Kerr.

enter image description here

He does declare two services:

version: '2'  
services:  
  users-service:
    build: ./users-service
    ports:
     - "8123:8123"
    depends_on:
     - db
    environment:
     - DATABASE_HOST=db
  db:
    build: ./test-database

With a dedicated Dockerfile for the database:

FROM mysql:5

ENV MYSQL_ROOT_PASSWORD 123  
ENV MYSQL_DATABASE users  
ENV MYSQL_USER users_service  
ENV MYSQL_PASSWORD 123

ADD setup.sql /docker-entrypoint-initdb.d
like image 120
VonC Avatar answered Feb 10 '23 05:02

VonC


Docker containers are designed to run a single command. The mysql installer expects the service it registered to automatically be started on the OS bootup, but that's not the case inside of a container.

The proper solution is to split these into two separate containers, one db container, and another nodejs/app container. Link and run the two together with a docker-compose configuration that automatically sets up the host names.

The less ideal option is supervisord which you can use to run and manage multiple processes inside of the container. You install it just like any other app, configure your db and node app as two services for supervisord to manage, and then launch supervisord as your container's run command.

like image 37
BMitch Avatar answered Feb 10 '23 06:02

BMitch