title: Setup Docker MySql Database and connect it to BE
body: <p>Installed Docker, downloaded the mysql image, using VS Code.
  This is my docker.compose.yml file:</p>
  <pre><code>version: '3'
  services:
    db:
      image: mysql:latest
      environment:
        MYSQL_DATABASE: 'db'
        # So you don't have to use root, but you can if you like
        MYSQL_USER: 'root'
        # You can use whatever password you like
        MYSQL_PASSWORD: 'root'
        # Password for root access
        MYSQL_ROOT_PASSWORD: 'root'
      ports:
        # &lt;Port exposed&gt; : &lt; MySQL Port running inside container&gt;
        - '3306:3306'
      #security_opt:
        #- seccomp:unconfined
      cap_add:
        - SYS_NICE  # CAP_SYS_NICE
      expose:
        # Opens port 3306 on the container
        - '3306'
        # Where our data will be persisted
      volumes:
        # this creates paths on the container 
        - my-db:/var/lib/mysql
        - my-db:/docker-entrypoint-initdb.d
  # Names our volume
  volumes:
    my-db:    
  </code></pre>
  <p>With the command &quot;docker compose up&quot;, I see and output, I see the image is running. I get this output:</p>
  <ul>
  <li>Container <strong>irp-backend_db_1</strong>  Created                                                        0.0s
  Attaching to db_1
  db_1  | 2021-06-10 13:23:30+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.25-1debian10 started.
  db_1  | 2021-06-10 13:23:30+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
  db_1  | 2021-06-10 13:23:30+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.25-1debian10 started.
  db_1  | 2021-06-10T13:23:30.769957Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.25) starting as process 1
  db_1  | 2021-06-10T13:23:30.791485Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
  db_1  | 2021-06-10T13:23:30.955342Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
  db_1  | 2021-06-10T13:23:31.047007Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
  db_1  | 2021-06-10T13:23:31.153833Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self
  signed.
  db_1  | 2021-06-10T13:23:31.154004Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
  db_1  | 2021-06-10T13:23:31.158189Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a
  different directory.
  db_1  | 2021-06-10T13:23:31.175606Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.25'  socket: '/var/run/mysqld/mysqld.sock'  <strong>port: 3306</strong>  MySQL Community Server - GPL.</li>
  </ul>
  <p>This is my config/config.json file:</p>
  <pre><code>{
    &quot;development&quot;: {
      &quot;username&quot;: &quot;root&quot;,
      &quot;password&quot;: &quot;root&quot;,
      &quot;database&quot;: &quot;database_development&quot;,
      &quot;host&quot;: &quot;localhost&quot;,
      &quot;dialect&quot;: &quot;mysql&quot;
    },
    &quot;test&quot;: {
      &quot;username&quot;: &quot;root&quot;,
      &quot;password&quot;: &quot;root&quot;,
      &quot;database&quot;: &quot;database_test&quot;,
      &quot;host&quot;: &quot;localhost&quot;,
      &quot;dialect&quot;: &quot;mysql&quot;
    },
    &quot;production&quot;: {
      &quot;username&quot;: &quot;root&quot;,
      &quot;password&quot;: &quot;root&quot;,
      &quot;database&quot;: &quot;database_production&quot;,
      &quot;host&quot;: &quot;localhost&quot;,
      &quot;dialect&quot;: &quot;mysql&quot;
    }
  }
  </code></pre>
  <p>My migrations/create-user.js</p>
  <pre><code>module.exports = {
    up: async (queryInterface, Sequelize) =&gt; {
      await queryInterface.createTable('Users', {
        id: {
          allowNull: false,
          autoIncrement: true,
          primaryKey: true,
          type: Sequelize.INTEGER
        },
        email: {
          type: Sequelize.STRING,
          allowNull: false
        },
        password: {
          type: Sequelize.STRING,
          allowNull: false
        },
        firstName: {
          type: Sequelize.STRING
        },
        lasrName: {
          type: Sequelize.STRING
        },
        createdAt: {
          allowNull: false,
          type: Sequelize.DATE
        },
        updatedAt: {
          allowNull: false,
          type: Sequelize.DATE
        }
      });
    },
    down: async (queryInterface, Sequelize) =&gt; {
      await queryInterface.dropTable('Users');
    }
   };
  </code></pre>
  <p>models/index.js</p>
  <pre><code>const fs = require('fs');
  const path = require('path');
  const Sequelize = require('sequelize');
  const basename = path.basename(__filename);
  const env = process.env.NODE_ENV || 'development';
  const config = require(__dirname + '/../config/config.json')[env];
  const db = {};
  
  let sequelize;
  if (config.use_env_variable) {
    sequelize = new Sequelize(process.env[config.use_env_variable], config);
  } else {
    sequelize = new Sequelize(config.database, config.username, config.password, config);
  }
  
  // go through all files and do sequelize
  fs
    .readdirSync(__dirname)
    .filter(file =&gt; {
      return (file.indexOf('.') !== 0) &amp;&amp; (file !== basename) &amp;&amp; (file.slice(-3) === '.js');
    })
    .forEach(file =&gt; {
      const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
      db[model.name] = model;
    });
  
  Object.keys(db).forEach(modelName =&gt; {
    if (db[modelName].associate) {
      db[modelName].associate(db);
    }
  });
  
  db.sequelize = sequelize;
  db.Sequelize = Sequelize;
  
  module.exports = db;
  </code></pre>
  <p>this is my model/User.js</p>
  <pre><code>const { Model } = require('sequelize');
  module.exports = (sequelize, DataTypes) =&gt; {
    class User extends Model {
      /**
       * Helper method for defining associations.
       * This method is not a part of Sequelize lifecycle.
       * The `models/index` file will call this method automatically.
       */
      static associate(models) {
        // define association here
      }
    };
    User.init({
      email: DataTypes.STRING,
      password: DataTypes.STRING,
      firstName: DataTypes.STRING,
      lasrName: DataTypes.STRING
    }, {
      sequelize,
      modelName: 'User',
    });
    return User;
  };
  </code></pre>
  <p>in order to have a more readable code I have a router
  routes/index.js</p>
  <pre><code>const express = require(&quot;express&quot;);
  const router = express.Router();
  
  /**
   * router files
   */
  
  const userRoutes = require(&quot;./user/index&quot;);
  const clientRoutes  = require(&quot;./client/index&quot;);
  
  /**
   * using route files
   */
  
  router.use(&quot;/users&quot;, userRoutes);
  
  router.get(&quot;/&quot;, (req, res) =&gt; {
    res.json({
      message: &quot;&quot;,
    });
  });
  
  module.exports = router;
  </code></pre>
  <p>and my user routes/user/index.js</p>
  <pre><code>const { Router } = require(&quot;express&quot;);
  const router = Router();
  
  const userController = require(&quot;../../controllers/UserController&quot;);
  
  // get requests
  router.get(&quot;/&quot;, userController.getUsers);
  router.get(&quot;/getUserByEmail/:email&quot;, userController.getUserByEmail);
  
  // post requests
  router.post(&quot;/register&quot;, userController.register);
  router.post(&quot;/login&quot;, userController.login);
  router.post(&quot;/setUserPassword&quot;, userController.setUserPassword);
  
  module.exports = router;
  </code></pre>
  <p>my package.json</p>
  <pre><code>{
    &quot;name&quot;: &quot;nodejs-express-sequelize-mysql&quot;,
    &quot;version&quot;: &quot;1.0.0&quot;,
    &quot;description&quot;: &quot;Node.js Rest Apis with Express, Sequelize &amp; MySQL&quot;,
    &quot;main&quot;: &quot;server.js&quot;,
    &quot;scripts&quot;: {
      &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;
    },
    &quot;keywords&quot;: [
      &quot;nodejs&quot;,
      &quot;express&quot;,
      &quot;rest&quot;,
      &quot;api&quot;,
      &quot;sequelize&quot;,
      &quot;mysql&quot;
    ],
    &quot;author&quot;: &quot;bezkoder&quot;,
    &quot;license&quot;: &quot;ISC&quot;,
    &quot;dependencies&quot;: {
      &quot;cors&quot;: &quot;^2.8.5&quot;,
      &quot;express&quot;: &quot;^4.17.1&quot;,
      &quot;mysql2&quot;: &quot;^2.0.2&quot;,
      &quot;sequelize&quot;: &quot;^5.21.2&quot;
    }
  }
  </code></pre>
  <p>my sequlize.js file</p>
  <pre><code>import Sequelize from 'sequelize'
  import UserModel from &quot;./models/User&quot;
  
  TAG = &quot;sequelize&quot;
  
                                       // fields in the config.json file
  const sequelizeSqlite = new Sequelize(&quot;database&quot;, &quot;username&quot;, &quot;password&quot;, {
      dialect: 'sqlite',
      storage: &quot;data/db/storage.sqlite&quot;
  })
  
  const UserSqlite = UserModel(sequelizeSqlite, Sequelize);
  
  sequelizeSqlite.sync()
      .then(() =&gt; {
          console.log(TAG, &quot;User db and user table have been created  with Sqlite&quot;);
      })
  
  module.exports(UserSqlite);
  </code></pre>
  <p>and last file
  server.js file:
  app.use(express.urlencoded({ extended: true }));</p>
  <pre><code>const db = require(&quot;./models&quot;);
  db.sequelize.sync();
  
  // simple route
  app.get(&quot;/&quot;, (req, res) =&gt; {
    res.json({ message: &quot;Welcome to The Backend.&quot; });
  });
  
  app.use(&quot;./api&quot;, routes);
  
  // set port, listen for requests
  const PORT = process.env.PORT || 3000;
  
  app.listen(PORT, () =&gt; {
    console.log(`Server is running on port ${PORT}.`);
  });
  </code></pre>
  <ol>
  <li>I run: docker compose up ... image is working, I can see it on the Docker for Windows</li>
  <li>I run node server.js ... it creates a table on the image, I can see it on the docker extension</li>
  <li>I can't run the project with npm start</li>
  </ol>
  <p>I get the following error:</p>
  <pre><code>  nodejs-express-sequelize-mysql@1.0.0 start C:\Users\Win-10\Desktop\IRP\irp-backend
   &gt; node server.js
  
   events.js:353
         throw er; // Unhandled 'error' event
         ^
  
   Error: listen EADDRINUSE: address already in use :::3000
       at Server.setupListenHandle [as _listen2] (net.js:1318:16)
       at listenInCluster (net.js:1366:12)
       at Server.listen (net.js:1452:7)
       at Function.listen (C:\Users\Win-10\Desktop\IRP\irp-     backend\node_modules\express\lib\application.js:618:24)
       at Object.&lt;anonymous&gt; (C:\Users\Win-10\Desktop\IRP\irp-backend\server.js:32:5)
       at Module._compile (internal/modules/cjs/loader.js:1068:30)
       at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
       at Module.load (internal/modules/cjs/loader.js:933:32)
       at Function.Module._load (internal/modules/cjs/loader.js:774:14)
       at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
       at internal/main/run_main_module.js:17:47
    Emitted 'error' event on Server instance at:
       at emitErrorNT (net.js:1345:8)
       at processTicksAndRejections (internal/process/task_queues.js:82:21) {
     code: 'EADDRINUSE',
     errno: -4091,
     syscall: 'listen',
     address: '::',
     port: 3000
   }
  </code></pre>
  <p>I can see the backend is working in browser localhost:3000
  White page with one line displayed: {&quot;message&quot;:&quot;Welcome to The Backend.&quot;} // my msg from server.js</p>
  <p>I am still missing something but I cant figure it out. Can you please help me.</p>