Skip to main content

Command Palette

Search for a command to run...

Deploy a Node.js App using Docker: Hands-On

Updated
3 min read

Project Difficulty: ⭐⭐

Project Goal: Package a Node.js application into a Docker image and expose the service on host port 3000.

My app:

If you're following, you can clone my source file here: https://github.com/adegram/taskboard-app.git

Step 1: The dockerfile

The involves creating a blueprint which Docker uses to build the image. In my configuration file I'm focused on selecting a lightweight base image, establishing a working directory, and managing dependency installation.

Important: This file must reside in the root directory of your project and named: dockerfile.

Step 2: The .dockerignore

This file tells the Docker daemon which files/dir to exclude when packaging the build context. It's good practice to not copy unnecessary and sensitive files (such as .env files, private keys) into the image.

Step 3: Image build

Now time to build the Docker image using the build command. This process packages the Node.js runtime, application dependencies, and source code into a versioned artifact. This step is simple:

Open terminal and verify if I am in the same directory as my dockerfile

Now run: docker build -t taskboard-app:1.0 .

This command builds a Docker image tagged with the name taskboard-app and version 1.0 using the configuration and files found in your current directory.

💡
view the build process

Step 4: Container Instantiation & Port Binding

Here I will deploy the image taskboard-app:1.0 into a container.

docker run -d --name myapp -p 3000:4045 taskboard-app:1.0 

In my terminal, I run this command in detached mode -d, named the container myapp, Implement port mapping to bridge the host’s port 3000 to the container’s internal application port 4045.

I now have my application running in a docker container with container id: f79239482d0bc5d3bbd2f332f9d2b69f0cb8f790e49bad753565ed3e50c015e0

💡
Tip

docker logs + containerId a command that allows you perform primary troubleshoot operations. This command is useful to me for troubleshooting and viewing my container running the Node.js application if it's initialized correctly and is listening for requests. By default, it retrieves all logs generated by a container since its creation.

docker logs f79239482d0bc5d3bbd2f332f9d2b69f0cb8f790e49bad7-53565ed3e50c015e0

docker exec -it + containerId sh a runtime Introspection command. This lets me execute an interactive shell (-it) within the running container and perform live environment verification and filesystem inspection.

docker exec -it f79239482d0bc5d3bbd2f332f9d2b69f0cb8f7-90e49bad753565ed3e50c015e0 sh

This is good for performing a wide range of administrative and diagnostic tasks, explore the filesystem, view modules, verify configuration files, inspect environment variables, test internal connectivity, install dependencies and more

The application running on host’s port 3000

More from this blog