Docker For Beginners

Docker For Beginners
Photo by Antoine Petitteville / Unsplash

This is a super basic docker tutorial for absolute beginners.

To start, you definitely need to install docker on your operating system as the first thing. This is quite straightforward. Just visit docker's site and follow the instructions.

Create A NodeJS Application

Let's create a simple NodeJS app with the following index.js file:

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 is listening on port ${port} ..`))
index.js

We'll need a package.json file as well, with express installed. Run the following commands to achieve that:

npm init -y
npm install express
commands to initialize node application

Now add the start script to package.json file:

{
  "name": "docker-for-beginners",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1"
  }
}
package.json

How do we dockerize this app?

Dockerize The Application

We'll start by creating a Dockerfile in the root directory of our project folder.

FROM node:12

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

ENV PORT=8080

EXPOSE 8080

CMD [ "npm", "start" ]
Dockerfile

Here's what it says:

  • Create an image from a base image called node:12.
  • The working directory inside the container would be /app.
  • Copy package*.json files to work dir.
  • Run the npm install command.
  • Copy everything from current dir to work dir.
  • Set environment var PORT=8080.
  • Expose the port 8080.
  • Run the final command npm start.

We'll also create a .dockerignore file to avoid copying over node_modules folder.

node_modules
.dockerignore

Build An Image

Once we have the above setup ready, we can finally build an image from the Dockerfile.

docker build -t omkar/myapp:1.0 .

The above command will build a docker image and will tag it in the following format: username/image-name:version. The . at the end specifies current directory as the path to the Dockerfile.

Run The Container

The built image can be run with the image_id or the tag_name:

docker run <image_id / tag_name> -d

Once the container runs you can visit https://localhost:8080 to see the live application in your browser.

More

Here's a list of a few more docker commands which you may find helpful.

List all the running containers:

docker ps

Stop a container:

docker stop container_id

Remove a container:

docker rm container_id

Enter a container using interactive mode:

docker exec -it container_id bash

Note that you can find a full list of these on the docker's site. We'll see how to use docker-compose in the future.