NodeJS + Mysql with Docker Compose 2

故事扮演 提交于 2019-12-06 01:31:34

问题


I´m trying to built a docker-compose file to deploy locally my NodeJS app that connects to a mysql server. I´ve tried everything ( read a lot of tutorials and some questions here in Stackoverflow ) but I keep getting the ECONNREFUSED error. This is my Dockerfile from NodeJS:

##Nodejs

FROM node:latest

RUN useradd --user-group --create-home --shell /bin/false app

ENV HOME=/home/app

COPY package.json npm-shrinkwrap.json $HOME/playerground/
RUN chown -R app:app $HOME/*

USER app 
WORKDIR $HOME/playerground
RUN npm cache clean && npm install --silent --progress=false

USER root
COPY . $HOME/playerground
RUN chown -R app:app $HOME/*
USER app

This is my Mysql Dockerfile:

FROM mysql:latest

ENV MYSQL_ROOT_PASSWORD root  
ENV MYSQL_DATABASE playerground  
ENV MYSQL_USER root  
ENV MYSQL_PASSWORD root

And this is my docker-compose:

version: '2'
services: 
  db:
    build: ./database
    ports:
      - "3307:3306"  
  playerground:
      build:
        context: .
        dockerfile: Dockerfile
      command: node_modules/.bin/nodemon --exec npm start
      environment:
        ENVIRONMENT: development
      ports:
        - "9090:9090"
      links:
        - db  
      volumes:      
        - .:/home/app/playerground
        - /home/app/playerground/node_modules

Another thing is my configuration file from Nodejs:

//Database
'development' : {
  'host' : process.env.HOSTNAME || 'localhost',
  'user' : 'root',
  'password' : 'root',
  'database' : 'playerground'
},
//Server
'development' : {
  'host' : process.env.HOSTNAME || '127.0.0.1',
  'port' : 3000
},

Can you help me? Thanks


回答1:


In your app config, the database host isn't pointing at your MySql container. You're pointing it at the local host, which is the app container. In the Compose file you can explicitly name the link to the db container using:

  links:
    - db:db  

And then your database container can be reached at the hostname db. You can hard-code that host in your app config, because it will be the same for all environments, as long as you use the same Compose file.

Also, if you're using a recent version of Docker you don't need to publish ports between containers in the same Docker network - so you can remove this from your Compose file:

ports:
  - "3307:3306"  

Then the db container will be accessible by the app container, but not externally.



来源:https://stackoverflow.com/questions/39581438/nodejs-mysql-with-docker-compose-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!