Let's create a sample NodeJs application.
Basically, it will create a folder name with myapp, in which the default `package.json` file will be created which will looks like below.
Now install express as a dependency package.
So now our NodeJs application is created successfully, now let's dockerize the same app.
Dockerfile
- A Dockerfile is a collection of all the commands a user could
initialize and call written in a text document, which later on assembles
into one image.
Step 3
Open the Dockerfile, write executable command lines that handling the
bundling of the app, and automatically runs the application in Docker
container.
- This command will identify that which build image we need to pull out, here we are using the latest LTS version of Node
- The build files which are generated will move to app folder directory, which is considered as a working directory
- This will copy the package.json files and install all dependent packages using package.json file, This command will not copy whole files or folder from the project, it will copy only package.json file,
- We must copy our source code or project file to a
working directory. To bundle that application's source code we have to
use COPY command.
- Now after copying app files, we need to define port on which the application will run, for that we have to use EXPOSE command that identifies the port number to run an application that is mapped in docker daemon.
-
At last, we need to provide executable command line that runs the
application, using CMD command you can run the application in a docker.
Your Dockerfile will look like below
Step 4 - Now add a .dockerignore
This file is not mandatory, but it's a good practice to have this file
which can help to boost the build process and make Docker Image to build unnecessary code and files.
Step 5 - Create a Docker Image / Build Docker Image
Let's run the docker build command which will help us to create Docker Image with NodeJs App.
Your image will now be listed by Docker like below
Step 6
In case you're using Docker Desktop, then you can see Docker Image in Docker Desktop. You just need to open Docker Desktop and run your published application by clicking on RUN button.
Step 7
After successfully running Docker Container, Docker Desktop will provide the URL which can be run in the browser.
Summary
In this article, we've learned how to Dockerize a NodeJs application,. This approach is on a beginner level - Docker provides large enhancement with its best use, so after learning the beginner
level Dockerizing you should learn more in detail about development and
production environment configuration.