The Complete Beginner's Guide to Docker

Docker is a powerful tool that allows you to create, run, and deploy applications using containers. Containers are isolated environments that contain everything you need to run your application, such as code, dependencies, configurations, etc. Containers are portable, scalable, and easy to manage. In this blog post, I will show you how to get started with Docker and create your first containerized application.

What is Docker?

Docker is a software platform that enables you to build, test, and deploy applications using containers. Docker uses a client-server architecture, where the Docker client communicates with the Docker daemon (or server) to perform various operations. The Docker daemon runs on a host machine and manages the containers, images, networks, volumes, and other resources. The Docker client can be a command-line interface (CLI) or a graphical user interface (GUI) such as Docker Desktop.

Why use Docker?

Docker has many benefits for developers and operators, such as:

  • Consistency: You can run your application in the same way on different platforms, such as your laptop, a virtual machine, or the cloud. You don’t have to worry about compatibility issues or configuration changes.

  • Isolation: You can isolate your application from other processes and resources on the host machine. This improves security, performance, and reliability.

  • Reusability: You can reuse existing images or create your own images based on other images. This reduces duplication and saves time and space.

  • Collaboration: You can share your images with others using Docker Hub, a public repository of images. You can also use private registries or other services to store and distribute your images.

  • Automation: You can automate the creation and deployment of your containers using tools such as Docker Compose, Docker Swarm, or Kubernetes. You can also integrate Docker with other tools such as Visual Studio Code, GitHub, Jenkins, etc.

How to install Docker?

Docker is available for different platforms such as Windows, macOS, Linux, etc. The installation process may vary depending on your operating system and hardware requirements. You can find the official installation instructions for each platform on the Docker website. For this tutorial, I will assume that you are using Windows 10 with WSL 2 enabled.

To install Docker on Windows 10 with WSL 2:

  • Download and install the latest version of Docker Desktop from the official website.

  • Follow the instructions to enable WSL 2 on your system.

  • Launch Docker Desktop and sign in with your Docker ID or create one if you don’t have one.

  • Verify that Docker is running by opening a terminal (such as PowerShell or Command Prompt) and typing docker version. You should see something like this:

Client: 
 Version:           20.10.6
 API version:       1.41
 Go version:        go1.16.3
 Git commit:        370c289
 Built:             Fri Apr  9 22:49:36 2021
 OS/Arch:           windows/amd64
 Context:           default
 Experimental:      true

Server: 
 Engine:
  Version:          20.10.6
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       8728dd2
  Built:            Fri Apr  9 22:44:56 2021
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          v1.4.4
  GitCommit:        05f951a3781f4f2c1911b05e61c160e9c30eaa8e
 runc:
  Version:          1.0.0-rc93
  GitCommit:        12644e614e25b05da6fd08a38ffa0cfe1903fdec
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

If you see something similar, congratulations! You have successfully installed Docker on your system.

How to create and run a container?

A container is a runnable instance of an image. An image is a file that contains all the information needed to create and run a container, such as code, dependencies, configurations, etc. You can create your own images or use existing images from Docker Hub or other sources.

To create and run a container using an existing image:

  • Open a terminal and type docker run hello-world. This command will pull the hello-world image from Docker Hub and run it as a container on your system.

  • You should see something like this:

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
b8dfde127a29: Pull complete 
Digest: sha256:f2266cbfc127c960fd30e76b7c792dc23b588c0db76233517e1891a4e357d519
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

This message shows that your container is running and printing some output to your terminal. It also gives you some suggestions on what to do next.

  • To see the list of containers running on your system, type docker ps. You should see something like this:
CONTAINER ID   IMAGE         COMMAND    CREATED          STATUS          PORTS     NAMES
54f4984ed6a8   hello-world   "/hello"   12 seconds ago   Up 11 seconds             nostalgic_shirley

This shows the details of your container, such as its ID, image, command, creation time, status, ports, and name. You can use these details to interact with your container.

  • To stop your container, type docker stop nostalgic_shirley. This will send a signal to your container to terminate gracefully. You can also use the container ID instead of the name.

  • To remove your container, type docker rm nostalgic_shirley. This will delete your container from your system. You can also use the -f flag to force the removal of a running container.

How to create and run a custom image?

To create your own image, you need to write a Dockerfile. A Dockerfile is a text file that contains instructions on how to build an image. You can use various commands in a Dockerfile, such as FROM, RUN, COPY, CMD, etc. You can find the reference for all the commands on the Docker website.

For this tutorial, we will create a simple web server using Node.js and Express. To do that, we need to:

  • Create a directory for our project and navigate to it.

  • Create a file named app.js and paste the following code:

// app.js
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello from Docker!');
});

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

This code creates a web server that listens on port 3000 and responds with “Hello from Docker!” when someone visits the root path.

  • Create a file named package.json and paste the following code:
{
  "name": "docker-web",
  "version": "1.0.0",
  "description": "A simple web server using Node.js and Express",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "^4.17.1"
  }
}

This file defines the metadata and dependencies of our project.

  • Create a file named Dockerfile and paste the following code:
# Dockerfile
# Use the official Node.js image as the base image
FROM node:latest

# Set the working directory inside the container
WORKDIR /usr/src/app

# Copy the package.json and package-lock.json files from your host to your current location inside the container
COPY package*.json ./

# Run the npm install command inside the container to install all the dependencies
RUN npm install

# Copy the rest of your code from your host to your current location inside the container
COPY . .

# Expose port 3000 to allow communication to/from server
EXPOSE 3000

# Define what command to run when the container is started
CMD [ "npm", "start" ]

This file defines how to build our image step by step.

  • To build our image, type docker build -t docker-web . in your terminal. This command will use the Dockerfile in the current directory to create an image named docker-web. You should see something like this:
Sending build context to Docker daemon  4.096kB
Step 1/7 : FROM node:latest
latest: Pulling from library/node
6ec8c9369e08: Pull complete 
a3ed95caeb02: Pull complete 
d1eef6b04d83: Pull complete 
0f4c1d8b5f3c: Pull complete 
a8f58c4fcca0: Pull complete 
e2b9c3fcb90a: Pull complete 
Digest: sha256:8dbefbfc2ad7a7cc6d487bba2c4db28012c6a34d44d6ee632933e5b11ad1ac90
Status: Downloaded newer image for node:latest
 ---> b590368a5593
Step 2/7 : WORKDIR /usr/src/app
 ---> Running in 9f0fadf30723
Removing intermediate container 9f0fadf30723
 ---> 8bb5d8c2adff
Step 3/7 : COPY package*.json ./
 ---> 0eaf1af5b538
Step 4/7 : RUN npm install
 ---> Running in 0d2fbb09f567

added 50 packages from 37 contributors and audited 50 packages in 1.178s

3 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Removing intermediate container 0d2fbb09f567
 ---> c0629a8b643b
Step 5/7 : COPY . .
 ---> e8f8b4f91eb7
Step 6/7 : EXPOSE 3000
 ---> Running in a9dd71a88296
Removing intermediate container a9dd71a88296
 ---> f9df1fafd224
Step 7/7 : CMD [ "npm", "start" ]
 ---> Running in c8f59c41b36c
Removing intermediate container c8f59c41b36c
 ---> a5e35d24e7da
Successfully built a5e35d24e7da
Successfully tagged docker-web:latest

This shows the progress of each step and the final image ID and tag.

  • To run your image as a container, type docker run -p 3000:3000 docker-web. We can also run this command in the background using docker run -d -p 3000:3000 docker-web .The -d flag stands for "detached mode." When you run a container in detached mode, the container will start in the background and not attach to your terminal. This means that you can continue using the terminal for other tasks while the container runs separately in the background. This command will map port 3000 of the container to port 3000 of the host machine and start the container with the default command (npm start).

  • You should see something like this:

> docker-web@1.0.0 start /usr/src/app
> node app.js

Server running at http://localhost:3000

This shows that your web server is running inside the container.

  • To access your web server from your browser, type http://localhost:3000 in the address bar. You should see a message saying “Hello from Docker!”.

Congratulations! You have successfully created and run your first custom image and container using Docker. I hope you enjoyed this tutorial and learned something new. If you want to learn more about Docker, you can visit the official documentation or check out some of the courses and books available online. Happy coding! 😊

Did you find this article valuable?

Support Vishesh Gubrani by becoming a sponsor. Any amount is appreciated!