Tuesday, April 28, 2020

Docker Assignments #11: Node.js, MySQL and Dockerfile

Create a folder structure as per below image in the host machine


  1. Pull mysql:5.7 docker image into host machine
  2. Write docker run command by setting following options
  • enable detached mode
  • set container name as "testmysql"
  • map host port number to 3500
  • set MYSQL_ROOT_PASSWORD as “mysql123”
      3. Check testmysql container up and running
       4. Enter container using docker exec
       5. Connect to database using mysql CLI client with root user
       6. Create database with name “hr”
       7. Create table with name employee and “id, name” columns under “hr” database
       8. Insert sample data into employee table  
      9. Check “HR” database and “Employee” table with data
      10. Add "mysql" npm package as a dependency in the package.json file
      11. Write required code into index.js file to connect "testmysql" container
      12. Configure Dockerfile with below instructions
  • set base image as "mhart/alpine-node"
  • set working directory  as "/usr/app"
  • copy all files from host machine and do npm install
  • run index.js file as startup command
    13. Build docker image with name "testnodemysqlimg"
    14. Write Docker run command by linking "testmysql" container

Step 1: 
     > docker pull mysql:5.7
Step 2: 
     > docker run -d -p 3500:3306 -e MYSQL_ROOT_PASSWORD=mysql123 --name testmysql mysql:5.7
Step 3: 
     > docker ps
Step 4: 
     > docker exec -it testmysql mysql -u root -p

Step 6: 
     mysql> create database hr;
     mysql> use hr;
     mysql> create table employee(id int,name varchar(10));
     mysql> insert into employee values(1,'rama');
     mysql> select * from employee;

Step 10: 
     > npm install mysql

Step 11: 
var mysql = require('mysql');
var con = mysql.createConnection({
  host"db", // alias name of linking container
  user"root",
  password"mysql123",
  port:"3306",
  database:'hr'
});
con.connect(function(err) {
  if (errthrow err;
  console.log("mysql connected successfully");

});
con.end();

Step 12: 
FROM mhart/alpine-node
WORKDIR /usr/app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node""index.js"]

Step 13:
docker build -t testnodemysqlimg .

Step 14:
docker run --link testmysql:db testnodemysqlimg
  • -- link testmysql:db --> "testmysql" is the mysql container name and "db" is the alias name. So, alias name will  act as mysql hostname 
docker run --link testmysql testnodemysqlimg
  •  --link testmysql --> "testmysql" is the mysql container name and it act as mysql hostname


Happy Coding :)

No comments:

Post a Comment