I am currently running Ubuntu 20.10 on a Raspberry Pi 3. I have already installed Docker and the MySQL server, which runs as a service on Ubuntu. Both of the installations are working properly. Now I am trying to run this Node.js API:
'use strict';
const express = require('express');
const mysql = require('mysql');
const PORT = 8080;
const HOST = '0.0.0.0';
const app = express();
app.get('/', (req, res) => {
  res.send('Hello World');
});
app.get('/persons', (req, res) => {
  connection.query('SELECT * FROM persons', (err, result) => {
    if (err) res.send(`Some error occured: ${err}`);
    res.send(result);
  });
});
app.listen(PORT, HOST);
console.log(`Runnning API on http://${HOST}:${PORT}`);
const connection = mysql.createConnection({
  host: 'localhost',
  user: myuser,
  password: 'mypwd,
  database: mydb
});
connection.connect(err => {
  if (err) throw err;
  console.log('Successfully connected to MySQL');
});
This works perfectly fine until I wrap this app into a Docker container. The Dockerfile looks like this:
FROM node:14
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8080
CMD [ "node", "server.js"]
Then I get this error:
if (err) throw err;
           ^
Error: connect ECONNREFUSED 127.0.0.1:3306
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1135:16)
    --------------------
    at Protocol._enqueue (/home/felix/workspaces/node-api/node_modules/mysql/lib/protocol/Protocol.js:144:48)
    at Protocol.handshake (/home/felix/workspaces/node-api/node_modules/mysql/lib/protocol/Protocol.js:51:23)
    at Connection.connect (/home/felix/workspaces/node-api/node_modules/mysql/lib/Connection.js:116:18)
    at Object.<anonymous> (/home/felix/workspaces/node-api/server.js:31:12)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47 {
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 3306,
  fatal: true
}
Does anyone know how to fix this? Moreover I wanted to know what`s the difference between running MySQL as a service on Linux or running it in a container…what are the advantages/disadvantages? Or can someone explain if it makes sense to run the app and the database in two different containers and connect them with Docker compose?
 
     
    