Containerizing a JavaScript Application
Now that you've got some idea of creating images, it's time to work with something a bit more relevant. In this sub-section, you'll be working with the source code of the fhsinchy/hello-dock image that you worked with on a previous section. In the process of containerizing this very simple application, you'll be introduced to volumes and multi-staged builds, two of the most important concepts in Docker.

Writing The Development Dockerfile

To begin with, open up the directory where you've cloned the repository that came with this article. Code for the hello-dock application resides inside the sub-directory with the same name.
This is a very simple JavaScript project powered by the vitejs/vite project. Don't worry though, you don't need to know JavaScript or vite in order to go through this sub-section. Having a basic understanding of Node.js and npm will suffice.
Just like any other project you've done in the previous sub-section, you'll begin by making a plan of how you want this application to run. In my opinion, the plan should be as follows:
  • Get a good base image for running JavaScript applications i.e. node.
  • Set the default working directory inside the image.
  • Copy the package.json file into the image.
  • Install necessary dependencies.
  • Copy rest of the project files.
  • Start the vite development server by executing npm run dev command.
This plan should always come from the developer of the application that you're containerizing. If you're the developer yourself, then you should already have a proper understanding of how this application needs to be run. Now if you put the above mentioned plan inside Dockerfile.dev, the file should look like as follows:
1
FROM node:lts-alpine
2
​
3
EXPOSE 3000
4
​
5
USER node
6
​
7
RUN mkdir -p /home/node/app
8
​
9
WORKDIR /home/node/app
10
​
11
COPY ./package.json .
12
RUN npm install
13
​
14
COPY . .
15
​
16
CMD [ "npm", "run", "dev" ]
Copied!
Explanation for this code is as follows:
  • The FROM instruction here sets the official Node.js image as the base giving you all the goodness of Node.js necessary to run any JavaScript application. The lts-alpine tag indicates that you want to use the Alpine variant, long term support version of the image. Available tags and necessary documentation for the image can be found on node hub page.
  • The USER instruction sets the default user for the image to node. By default Docker runs containers as the root user and according to Docker and Node.js Best Practices this can pose a security threat. So a better idea is to run as a non-root user whenever possible. The node image comes with a non-root user named node which you can set as the default user using the USER instruction.
  • The RUN mkdir -p /home/node/app instruction creates a directory called app inside the home directory of the node user. The home directory for any non-root user in Linux is usually /home/<user name> by default.
  • Then the WORKDIR instruction sets the default working directory to the newly created /home/node/app directory. By default the working directory of any image is the root. You don't want any unnecessary files sprayed all over your root directory, do you? Hence you change the default working directory to something more sensible like /home/node/app or whatever you like. This working directory will be applicable to any subsequent COPY, ADD, RUN and CMD instructions.
  • The COPY instruction here copies the package.json file which contains information regarding all the necessary dependencies for this application. The RUN instruction executes npm install command which is the default command for installing dependencies using a package.json file in Node.js projects. The . at the end represents the working directory.
  • The second COPY instruction copies rest of the content from the current directory (.) of the host filesystem to the working directory (.) inside the image.
  • Finally, the CMD instruction here sets the default command for this image which is npm run dev written in exec form.
  • The vite development server by default runs on port 3000 hence adding an EXPOSE command seemed like a good idea, so there you go.
Now, to build an image from this Dockerfile.dev you can execute the following command:
1
docker image build --file Dockerfile.dev --tag hello-dock:dev .
2
​
3
# Step 1/7 : FROM node:lts
4
# ---> b90fa0d7cbd1
5
# Step 2/7 : EXPOSE 3000
6
# ---> Running in 722d639badc7
7
# Removing intermediate container 722d639badc7
8
# ---> e2a8aa88790e
9
# Step 3/7 : WORKDIR /app
10
# ---> Running in 998e254b4d22
11
# Removing intermediate container 998e254b4d22
12
# ---> 6bd4c42892a4
13
# Step 4/7 : COPY ./package.json .
14
# ---> 24fc5164a1dc
15
# Step 5/7 : RUN npm install
16
# ---> Running in 23b4de3f930b
17
### LONG INSTALLATION STUFF GOES HERE ###
18
# Removing intermediate container 23b4de3f930b
19
# ---> c17ecb19a210
20
# Step 6/7 : COPY . .
21
# ---> afb6d9a1bc76
22
# Step 7/7 : CMD [ "npm", "run", "dev" ]
23
# ---> Running in a7ff529c28fe
24
# Removing intermediate container a7ff529c28fe
25
# ---> 1792250adb79
26
# Successfully built 1792250adb79
27
# Successfully tagged hello-dock:dev
Copied!
Given the filename is not Dockerfile you have to explicitly pass the filename using the --file option. A container can be run using this image by executing the following command:
1
docker container run \
2
--rm \
3
--detach \
4
--publish 3000:3000 \
5
--name hello-dock-dev \
6
hello-dock:dev
7
​
8
# 21b9b1499d195d85e81f0e8bce08f43a64b63d589c5f15cbbd0b9c0cb07ae268
Copied!
Now visit http://127.0.0.1:3000 to see the hello-dock application in action.
Congratulations on running your first real-world application inside a container. The code you've just written is okay but there is one big issue with it and there are a few places where it can be improved. Let's begin with the issue first.

Working With Bind Mounts

If you've worked with any front-end JavaScript framework before, you should know that the development servers in these frameworks usually come with a hot reload feature. That is if you make a change in your code, the server will reload automatically reflecting any changes you've made immediately.
But if you make any change in your code right now, you'll see nothing happening to your application running in the browser. The reason behind this is the fact that you're making changes in the code that you have in your local file system but the application you're seeing in the browser resides inside the container file system.
To solve this issue, you can again make use of a bind mount. You've already had a brief encounter of bind mounts in the Working With Executable Images sub-section.
Using bind mounts, you can easily mount one of your local file system directory inside a container. Instead of making a copy of the local file system, the bind mount can reference the local file system directly from inside the container.
This way, any changes you make to your local source code will reflect immediately inside the container, triggering the hot reload feature of vite development server. Changes made to the file system inside the container will reflect on your local file system as well.
You've already learned in the Working With Executable Images sub-section, bind mounts can be created using the --volume or -v option for the container run or container start commands. Just to remind you, the generic syntax is as follows:
1
--volume <local file system directory absolute path>:<container file system directory absolute path>:<read write access>
Copied!
Stop your previously started hello-dock-dev container, and start a new container by executing the following command:
1
docker container run \
2
--rm \
3
--publish 3000:3000 \
4
--name hello-dock-dev \
5
--volume $(pwd):/home/node/app \
6
hello-dock:dev
7
​
8
# sh: 1: vite: not found
9
# npm ERR! code ELIFECYCLE
10
# npm ERR! syscall spawn
11
# npm ERR! file sh
12
# npm ERR! errno ENOENT
13
# npm ERR! [email protected] dev: `vite`
14
# npm ERR! spawn ENOENT
15
# npm ERR!
16
# npm ERR! Failed at the [email protected] dev script.
17
# npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
18
# npm WARN Local package.json exists, but node_modules missing, did you mean to install?
Copied!
Keep in mind, I've omitted the --detach option and that's to demonstrate a very important point. As you can see that the application is not running at all now.
That's because although the usage of a volume solves the issue of hot reloads, it introduces another one. If you have any previous experience with Node.js, you may know that the dependencies of a Node.js project lives inside the node_modules directory on the project root.
Now that you're mounting the project root on your local file system as a volume inside the container, the content inside the container gets replaced along with the node_modules directory containing all the dependencies. Hence the vite package goes missing.

Working With Anonymous Volumes

This problem here can be solved using an anonymous volume. An anonymous volume is identical to a bind mount except the fact that you don't need to specify the source directory here. The generic syntax for creating an anonymous volume is as follows:
1
--volume <container file system directory absolute path>:<read write access>
Copied!
So the final command for starting the hello-dock container with both volumes should be as follows:
1
docker container run \
2
--rm \
3
--detach \
4
--publish 3000:3000 \
5
--name hello-dock-dev \
6
--volume $(pwd):/home/node/app \
7
--volume /home/node/app/node_modules \
8
hello-dock:dev
9
​
10
# 53d1cfdb3ef148eb6370e338749836160f75f076d0fbec3c2a9b059a8992de8b
Copied!
Here, Docker will take the entire node_modules directory from inside the container and tuck it away in some other directory managed by the Docker daemon on your host file system and will mount that directory as node_modules inside the container.

Performing Multi-Staged Builds

So far in this section, you've built an image for running a JavaScript application in development mode. Now if you want to build the image in production mode, some new challenges show up. In development mode the npm run serve command starts a development server that serves the application to the user. That server not only serves the files but also provides the hot reload feature.
In production mode, the npm run build command compiles all your JavaScript code into some static HTML, CSS and JavaScript files. To run these files you don't need node or any other runtime dependencies. All you need is a server like nginx for example.
So to create an image where the application runs in production mode, you can take the following steps:
  • Use node as the base image and build the application.
  • Install nginx inside the node image and use that to serve the static files.
This approach is a completely valid but the problem is that the node image is big and most of the stuff it carries is unnecessary to serve your static files. A better approach to this scenario is as follows:
  • Use node image as the base and build the application.
  • Copy the files created using the node image to a nginx image.
  • Create the final image based on nginx and discard all node related stuff.
This way your image only contains the files that are needed and becomes really handy. This approach is a multi-staged build. To perform such a build, create a new Dockerfile inside your hello-dock project directory and put following content in there:
1
FROM node:lts-alpine as builder
2
​
3
WORKDIR /app
4
​
5
COPY ./package.json ./
6
RUN npm install
7
​
8
COPY . .
9
RUN npm run build
10
​
11
FROM nginx:stable-alpine
12
​
13
EXPOSE 80
14
​
15
COPY --from=builder /app/dist /usr/share/nginx/html
Copied!
As you can see the Dockerfile looks a lot like your previous ones with a few oddities. Explanation for this file is as follows:
  • Line 1 starts the first stage of the build using node:lts-alpine as the base image. The as builder syntax assigns a name to this stage so that it can be referred to later on.
  • From line 3 to line 9, it's standard stuff that you've seen many times before. The RUN npm run build command actually compiles the entire application and tucks it inside /app/dist directory where /app is the working directory and /dist is the default output directory for vite applications.
  • Line 11 starts the second stage of the build using nginx:stable-alpine as the base image.
  • The NGINX server runs on port 80 by default hence the line EXPOSE 80 is added.
  • The last line is a COPY instruction. The --from=builder part indicates that you want to copy some files from the builder stage. After that it's a standard copy instruction where /app/dist is the source and /usr/share/nginx/html is the destination. The destination used here is the default site path for NGINX so any static file you put inside there will be automatically served.
As you can see the resultant image is a nginx base image containing only the files necessary for running the application. To build this image execute following command:
1
docker image build --tag hello-dock:prod .
2
​
3
# Step 1/9 : FROM node:lts-alpine as builder
4
# ---> 72aaced1868f
5
# Step 2/9 : WORKDIR /app
6
# ---> Running in e361c5c866dd
7
# Removing intermediate container e361c5c866dd
8
# ---> 241b4b97b34c
9
# Step 3/9 : COPY ./package.json ./
10
# ---> 6c594c5d2300
11
# Step 4/9 : RUN npm install
12
# ---> Running in 6dfabf0ee9f8
13
# npm WARN deprecated [email protected]: Please update to v 2.2.x
14
#
15
# > [email protected] postinstall /app/node_modules/esbuild
16
# > node install.js
17
#
18
# npm notice created a lockfile as package-lock.json. You should commit this file.
19
# npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected]~2.1.2 (node_modules/chokidar/node_modules/fsevents):
20
# npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
21
# npm WARN [email protected] No description
22
# npm WARN [email protected] No repository field.
23
# npm WARN [email protected] No license field.
24
#
25
# added 327 packages from 301 contributors and audited 329 packages in 35.971s
26
#
27
# 26 packages are looking for funding
28
# run `npm fund` for details
29
#
30
# found 0 vulnerabilities
31
#
32
# Removing intermediate container 6dfabf0ee9f8
33
# ---> 21fd1b065314
34
# Step 5/9 : COPY . .
35
# ---> 43243f95bff7
36
# Step 6/9 : RUN npm run build
37
# ---> Running in 4d918cf18584
38
#
39
# > [email protected] build /app
40
# > vite build
41
#
42
# - Building production bundle...
43
#
44
# [write] dist/index.html 0.39kb, brotli: 0.15kb
45
# [write] dist/_assets/docker-handbook-github.3adb4865.webp 12.32kb
46
# [write] dist/_assets/index.eabcae90.js 42.56kb, brotli: 15.40kb
47
# [write] dist/_assets/style.0637ccc5.css 0.16kb, brotli: 0.10kb
48
# - Building production bundle...
49
#
50
# Build completed in 1.71s.
51
#
52
# Removing intermediate container 4d918cf18584
53
# ---> 187fb3e82d0d
54
# Step 7/9 : EXPOSE 80
55
# ---> Running in b3aab5cf5975
56
# Removing intermediate container b3aab5cf5975
57
# ---> d6fcc058cfda
58
# Step 8/9 : FROM nginx:stable-alpine
59
# stable: Pulling from library/nginx
60
# 6ec7b7d162b2: Already exists
61
# 43876acb2da3: Pull complete
62
# 7a79edd1e27b: Pull complete
63
# eea03077c87e: Pull complete
64
# eba7631b45c5: Pull complete
65
# Digest: sha256:2eea9f5d6fff078ad6cc6c961ab11b8314efd91fb8480b5d054c7057a619e0c3
66
# Status: Downloaded newer image for nginx:stable
67
# ---> 05f64a802c26
68
# Step 9/9 : COPY --from=builder /app/dist /usr/share/nginx/html
69
# ---> 8c6dfc34a10d
70
# Successfully built 8c6dfc34a10d
71
# Successfully tagged hello-dock:prod
Copied!
Once the image has been built, you may run a new container by executing the following command:
1
docker container run \
2
--rm \
3
--detach \
4
--name hello-dock-prod \
5
--publish 8080:80 \
6
hello-dock:prod
7
​
8
# 224aaba432bb09aca518fdd0365875895c2f5121eb668b2e7b2d5a99c019b953
Copied!
The running application should be available on http://127.0.0.1:8080 address:
Here you can see my hello-dock application in all it's glory. Multi-staged builds can be very useful if you're building large applications with a lot of dependencies. If configured properly, images built in multiple stages can be very optimized and compact.

Ignoring Unnecessary Files

If you've been working with git for some time now, you may know about the .gitignore files in projects, containing a list of files and directories to be excluded from the repository. Well Docker has a similar concept. The .dockerignore file contains a list of files and directories to be excluded from image builds. You can find a pre-created .dockerignore file in the hello-dock directory.
1
.git
2
*Dockerfile*
3
*docker-compose*
4
node_modules
Copied!
This .dockerignore file has to be in the build context. Files and directories mentioned here will be ignored by the COPY instruction but if you do a bind mount, the .dockerignore file will have no effect. I've added .dockerignore files where necessary in the project repository.
Last modified 8mo ago