Jean Robert
Jean Robert

Reputation: 759

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.

Upvotes: 4

Views: 4270

Answers (3)

Nungster
Nungster

Reputation: 726

Use docker-compose and create a dockerfile for your nodejs and one for mysql. Each container is responsible for doing their thing. In your compose, link them. Then point your nodejs db connection to the mysql container.

Upvotes: 1

VonC
VonC

Reputation: 1329692

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

Upvotes: 4

BMitch
BMitch

Reputation: 265130

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.

Upvotes: 3

Related Questions