Docker and MySQL can't connect
I can’t for the life of me figure this out. I feel like I’m really close, but im just not quite there yet. Here’s my Dockerfile:
FROM ubuntu:14.04 MAINTAINER Oscar Godson RUN apt-get update RUN apt-get install -y nodejs-legacy RUN apt-get install -y npm RUN apt-get install -y mysql-server RUN apt-get install -y mysql-client COPY . /src WORKDIR /src RUN service mysql start;\ mysql -u root < /src/bin/demo-data.sql;\ npm install EXPOSE 4000 CMD ["node", "index.js"]
If i go into interactive mode and go into bash in that
RUN service... line at the end I can see that mysql is running, the demo data was imported and everything works including starting my Node app with
node index.js. If I then try to do another
RUN or the
CMD you see below it no longer can access MySQL. It’s like it stops running.
The error I get
Error: connect ECONNREFUSED which happens when it’s down or the data isn’t there. From me playing with it it looks like MySQL isn’t running if I try to access it after the
RUN where I start it.
P.S. The MySQL DB here is purely for development. On production we use AWS RDS, so thats why its using root without any password and importing data that way.
One Solution collect form web for “Docker and MySQL can't connect”
The problem was that
RUN shouldn’t be used for long running processes, however, you can only use one
CMD option. For some reason it didn’t click with me until a friend pointed it out, but I could just make a “installer.sh” script and call that with
CMD. Now it’s not losing the MySQL context. My update Dockerfile looks something like this:
FROM ubuntu:14.04 MAINTAINER Oscar Godson RUN apt-get update RUN apt-get install -y nodejs-legacy RUN apt-get install -y npm RUN apt-get install -y mysql-server RUN apt-get install -y mysql-client COPY . /src WORKDIR /src RUN cd /src;npm install EXPOSE 4000 CMD ./bin/installer.sh
Installer than has
service mysql start mysql -u root < ./bin/demo-data.sql node index.js