Have you ever tried to deploy your application somewhere outside of your local machine? Running a developed product (for example, a Node.js server) on another computer is sometimes a difficult task.
Software dependencies, environment variables, configuration files—all of these need to be configured to get the simplest application running. And doing it manually is a routine and unreliable job. We need automation.
Many modern technologies strive to solve the problem of different environments. Containerization is one of these options. And Docker is the most commonly used tool here.
Before you start following this guide, make sure you already have:
a cloud server running Ubuntu
Node.js installed
Docker installed
This tutorial assumes that the reader already has experience with the Node.js platform and is familiar with Docker.
Docker allows you to package your application, environment, and dependencies into a container.
First, we create an application image: code, libraries, configuration files, environment variables, and environment. Everything inside the image is needed to build and run the application.
A container directly refers to an instance of this image. If we draw an analogy from programming languages, then an image is a class, and a container is an instance of this class.
Unlike a virtual machine, a container is just an operating system process.
Essentially, Docker creates an abstraction over low-level operating system tools, allowing one or more containerized processes to run inside virtualized instances of the Linux operating system.
Despite the fact that Docker is by no means a panacea for deployment automation, it solves many important problems:
Deploys applications quickly
Provides portability between machines
Has version control
Allows you to build a flexible architecture using components
Reduces maintenance overhead due to its compact size
First, you need to create a directory for the application source files. Let's call it node_app
:
mkdir node_app
Now, move to this directory:
cd node_app
As with any Node.js project, we will need a configuration file. Let's create and open it. On Linux, this can be done via nano
:
nano package.json
Our project's details are standard:
{
"name": "node-app-by-hostman",
"description": "node with docker",
"version": "1.0.0",
"main": "hostman.js",
"keywords": [
"nodejs"
"express",
"docker"
],
"dependencies": {
"express": "^4.16.4"
},
"scripts": {
"start": "node hostman.js"
}
}
This file contains general information about the project, author, and license. It is needed for the NPM package manager, which is responsible for installing dependencies and publishing projects to the official library.
The most important parameters in this package.json
are:
The main entry point for the application is the hostman.js
file.
In the dependencies
, we specify the Express framework.
You can now save and close the file. All that remains is to install the dependencies:
npm install
For our example, we will create a simple Node.js application that displays a static web page: index.html.
The file structure is like this:
hostman.js
is the entry point that processes requests and performs routing;
index.html
is web page markup.
It is worth noting that to simplify the example, we will write CSS styles directly in HTML. Of course, in real projects, the visual description of a web page is located in separate files like style.css, often using SASS, LESS, or SCSS transpilers.
Using nano
, we will create and open hostman.js
:
nano hostman.js
It will only contain the bare minimum code to run the web server:
const express = require('express'); // requiring the Express framework (module)
const app = express(); // creating an application instance
const router = express.Router(); // creating a router instance
const path = __dirname; // path to the working directory
const port = 8080; // server port
// print HTTP METHOD to the console on every request
router.use(function (req,res,next) {
console.log('/' + req.method);
next();
});
// respond to the main page request with the index.html file
router.get('/', function(req,res){
res.sendFile(path + 'index.html');
});
// connect the router to the application
app.use('/', router);
// start listening on port 8080, thereby starting the http server
app.listen(port, function () {
console.log('Listening on port 8080')
})
The official Express documentation provides a more detailed description of the framework's functionality and examples of its use.
The HTML markup file index.html
looks pretty trivial:
<!DOCTYPE html>
<html lang="en">
<head>
<title>NodeJS app with Docker by Hostman</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div>Hello World from Hostman!</div>
</body>
<style>
body
{
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
body > div
{
padding: 12px;
color: white;
font-weight: bold;
background: black;
}
</style>
</html>
To make sure everything displays correctly, open the index.html file in your browser. You should see "Hello World from Hostman!" in the central part of the page, along with a dark border.
At this point, our improvised application can be considered complete. Now, we can move on to dockerization itself.
A Dockerfile is a text document that contains instructions for building a Docker image.
All instructions are executed exactly in the order in which they are written in this file. The recording format is simple: the instruction name and its arguments. This is somewhat similar to functions in programming languages. Comments are written after #
.
# comment
INSTRUCTION arguments
Although instruction names are not case-sensitive, they are usually written in capital letters so they do not visually blend with the arguments.
Let's create and open a Dockerfile, after which we can move on to editing it:
nano Dockerfile
Docker will consecutively execute the instructions in the Dockerfile each time an end user deploys your Node.js application.
Therefore, the first thing they will need is Node itself. Add the following instruction to the Dockerfile:
FROM node:19-alpine
In this case, the FROM
command installs the official image of Node.js Alpine Linux version 19 on the machine.
By the way, Docker has an official Docker Hub library that stores container images from developers all over the world. Of course, it also has Node.js.
If you look at the Node.js code on GitHub, you will notice a similar Dockerfile that sets up the environment for running Node on the user's machine.
To make a very simple analogy, a Dockerfile in Docker is almost the same as package.json
in NPM. It sets up the project and recursively "drags" all the dependencies: a higher-level Dockerfile installs an image with a lower-level Dockerfile, and so on.
The Docker image (which will later turn into a container) needs to be told in which directory to run the rest of the commands that will operate on files and folders. For example, RUN
, CMD
, ENTRYPOINT
, COPY
or ADD
commands.
To do this, there is a WORKDIR
instruction, which passes the directory path as an argument:
WORKDIR /app
Using the COPY
command, you need to copy the package.json
and package-lock.json
files from the project directory on the local computer to the container's file system - to the directory specified earlier:
COPY package.json package-lock.json ./
Because the Dockerfile is located in the project directory, the container image contains all the necessary files. However, an image is not a container. Therefore, using the COPY
command, we tell Docker which specific files need to be transferred to the "virtual space" of the container.
Since the previously installed application directory already contains package.json
and package-lock.json
, you can download the required dependencies from the NPM registry.
For these purposes, you usually run the npm install command. For Docker to do this automatically, you need to specify the RUN
instruction:
RUN npm install
Docker will execute this command in the previously specified /app
directory.
Note that the RUN
statement executes commands while installing the image (not starting the container), which will later exist as a container. By the way, you can enter commands like this:
RUN [“command1”, “command2”, “command3”]
Once all dependencies are installed, you can copy all the remaining project files to the /app
directory. To do this, use the same COPY
command, but specify the entire directory rather than specific files:
COPY. ./
Now you can enter the command to deploy your Node.js app. Use the CMD
instruction for this. Unlike the RUN
instruction, CMD
executes the specified commands while the container is running, not during the image installation:
cmd npm start
Don't forget that you already have the start command defined in package.json
:
"scripts": {
"start": "node hostman.js"
}
So, after we outlined the entire sequence of actions for Docker, the complete Dockerfile code should look like this:
# install the official Node.js image
FROM node:19-alpine
# specify the working (root) directory
WORKDIR /app
# copy the main application files to the working directory
COPY package.json package-lock.json ./
# install the specified NPM dependencies during the image installation stage
RUN npm install
# after installation, copy all project files to the root directory
COPY. ./
# run the main script when the container starts
cmd npm start
That's it! The minimum set of instructions is specified. Now you can try to create an image and run a container based on it.
.dockerignore
is another configuration file. It contains directories that should be excluded when creating the Docker image. Your project folder probably has a lot of files that are in no way related to the image we create, although they are important during development.
In fact, .dockerignore
is much more important than it might seem at first glance. It prevents files that are too large or sensitive from getting into the image. It also limits the effect of ADD
or COPY
commands used in the Dockerfile.
For example, every time you use the docker build command, Docker checks the image cache against the file system's state. If there are changes, it builds the image again.
However, if some files in your directory are updated quite often, but are not needed to build the image, they should be excluded so as not to perform a pointless rebuild.
The .dockerignore
file should be created in the root directory of your project. Inside the file, on each new line, indicate the names of files and directories to be excluded.
# this is a comment
README.md
Like in a Dockerfile, the #
symbol marks a comment.
There are also ways to specify files more generally:
*/folder
In this case, all directories (or files without an extension) with the name folder in any directory one level below will be excluded from the build.
However, you can ignore directories and files recursively, at the root and at all levels below:
**/folder
At the same time, using !
, you can exculde a specific file from the exception.
In this case, we will exclude all .md
files except README.md
:
*.md
!README.md
The Docker image is created based on the description in the Dockerfile. The command for this should be run from the root of the project, where the Dockerfile is located:
dockerbuild. -t nodeproject
The -t
flag is required to set the tag name of the new image. It can later be referenced via nodeproject:latest
.
After this, you can check that the image was actually created:
docker images nodeproject:latest
This command displays information about a specific Docker image:
REPOSITORY TAG IMAGE ID CREATED SIZE
nodeproject latest gk8orf8fre489 3 minutes ago 15MB
You do not need to enter a specific name, the console will display information about all images on the computer.
Each created image can be run as a container:
docker run nodeproject
Running as a container, a Docker image is an operating system process in which the file system, network, and process tree are separate from the host computer.
All console output from your Node.js application will be printed to the same terminal in which the container was launched. However, binding a container process to a specific terminal instance is not the best solution.
A better practice is to run the container in the background using the special --detach
or -d
flags.
docker run -d nodeproject
Docker will start the container by outputting a special identifier in the terminal. It can be used to access the container in subsequent commands:
9341f8b2532b121e9dea8aeb55563c24302df96710c411c699a612e794e89ee4
Before each container run, always check whether the container has already been launched unless you are sure it is not.
For this, Docker has a command that displays a list of all containers running on the computer:
docker ps
This way you can see the container ID, the image that the container is running on, the command used to start the container, the time it was created, the current status, the ports exposed by the container, and the name of the container itself. By default, Docker assigns a random name to the container, but this can be changed using the --name
flag.
Please note that we are talking about the name of the container, not the image. Let's say you run a container called myname
:
docker run -d --name myname nodeproject
Now you can stop it by specifying a name:
docker stop myname
And also remove:
docker rm myname
A container running in the background does not explicitly display output to the console. However, it exists and can be seen like this:
docker logs myname
Now everything that your application managed to output to the console will be printed in the terminal.
This article very briefly explains what Docker is, how it works, and why it can be useful when developing Node applications.
By understanding how to properly format a Dockerfile and deploy a Node.js application using Docker, you can automate the process of deploying software to end-user machines.
Such solutions are most relevant in DevOps development, in particular when building CI/CD pipelines.