Docker

  • Containers are an abstraction at the app layer that packages code and dependencies together.

  • Multiple containers can run on the same machine and share the OS kernel with other containers, each running as isolated processes in user space.

  • Docker is an open-source project that automates the deployment of software applications inside containers by providing an additional layer of abstraction and automation of OS-level virtualization on Linux.

Setting up Docker

You can follow Docker for Mac or Docker for Windows to install Docker on your machine. Once you are done installing Docker, test your Docker installation by running the following:

$ docker run hello-world

Docker images and Containers

Docker containers are instances of Docker images, whether running or stopped. In fact, the major difference between Docker containers and images is that containers have a writable layer.

Dockerfile

It is a text document that contains all the commands a user could call on the command line to assemble an image.

  1. In the below Dockerfile, first, we create and set the working directory using WORKDIR.
  2. We then copy files using the COPY command. The first argument is the source path, and the second is the destination path on the image file system.
  3. We install our project dependencies using npm install. This will create the node_modules directory.
  4. Exposing port 3000 informs Docker which port the container is listening on at runtime.
  5. The CMD command tells Docker how to run the application we packaged in the image. The CMD follows the format CMD [“command”, “argument1”, “argument2”].

     # Filename: Dockerfile 
     FROM node:12.9.1
     RUN mkdir -p /Users/vaswal/docker-dir
     WORKDIR /Users/vaswal/docker-dir
     COPY . .
     RUN npm install
     EXPOSE 3000
     CMD [ "npm", "start" ]
    

Building Docker images

With Dockerfile written, you can build the image using the following command:

$ docker build

We can see the image we just built using the command docker images.

$ docker images

Running a Docker image

You run a Docker image by using the docker run API. The command is as follows:

$ docker run -p80:3000 yourusername/example-node-app

The command is pretty simple. We supplied -p argument to specify what port on the host machine to map the port the app is listening on in the container. Now you can access your app from your browser on https://localhost:3000.