Docker Basics Tutorial with Node.js

Code Breakdown

Dockerfile

A Dockerfile is like DNA for building a Docker Image.

file_type_docker Dockerfile
FROM node:12

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

ENV PORT=8080

EXPOSE 8080

CMD [ "npm", "start" ]

Dockerignore

A Dockerignore file is required so we don’t add the node_modules folder to the image.

file_type_docker .dockerignore
node_modules

Node.js App

This is the code we went to run as the container’s process.

file_type_js src/index.js
const app = require('express')();

app.get('/', (req, res ) => 
    res.json({ message: 'Docker is easy 🐳' }) 
);

const port = process.env.PORT || 8080;

app.listen(port, () => console.log(`app listening on http://localhost:${port}`) );

Commands

Build the Image

command line
docker build -t fireship/demoapp:1.0 .

Run the Container

This maps the local port 5000 to the docker port 8080. You should be able to view the app on your local system at https://localhost:5000. You can choose any port you want.

command line
docker run -p 5000:8080 <image-id>

Docker Compose

Docker Compose makes it easy to manage multiple containers and volumes.

file_type_light_yaml docker-compose.yml
version: '3'
services:
  web:
    build: .
    ports:
      - "8080:8080"
  db:
    image: "mysql"
    environment: 
      MYSQL_ROOT_PASSWORD: password
    volumes:
      - db-data:/foo

volumes:
  db-data:

Run multiple Containers

command line
docker-compose up

Docker in 100s

Questions? Let's chat

Open Discord