Today's Topic - Docker Container for a template of Node.js App.

 

Image for a simple Node.js App.

This post explains the process of taking a Dockerfile, building a Docker image from it, and then running a Docker container based on that image.

Prerequisites

Before you begin, ensure you have Docker installed and running on your system:

  • Docker Desktop: For Windows and macOS users, download and install Docker Desktop from the official Docker website.

  • Docker Engine: For Linux users, follow the installation instructions for Docker Engine on the official Docker documentation.

Verify Docker is running by opening your terminal or command prompt and typing:

docker --version

Step 1: Create Your Dockerfile and Application Files

A Dockerfile is a text file that contains all the commands a user could call on the command line to assemble an image. It's typically named Dockerfile (without any file extension).

Let's create a simple Node.js application to demonstrate.

  1. Create a new directory for your project:
    mkdir my-docker-app
    cd my-docker-app

  2. Create the Dockerfile inside my-docker-app with the following content:
    # Use an official Node.js runtime as a parent image.
    # 'alpine' variants are smaller and more secure.
    FROM node:18-alpine

    # Set the working directory inside the container.
    # All subsequent commands will run from this directory.
    WORKDIR /app

    # Copy package.json and package-lock.json first.
    # This allows Docker to cache this layer if dependencies don't change,
    # speeding up subsequent builds.
    COPY package*.json ./

    # Install application dependencies.
    RUN npm install

    # Copy the rest of the application code into the container's working directory.
    COPY . .

    # Expose port 3000 to the outside world.
    # This informs Docker that the container listens on this port at runtime.
    EXPOSE 3000

    # Define the command to run the application when the container starts.
    # This uses the 'exec' form, which is recommended.
    CMD [ "node", "app.js" ]

  3. Create app.js (your Node.js application) in the same my-docker-app directory:
    const http = require('http');

    const hostname = '0.0.0.0'; // Listen on all network interfaces
    const port = 3000;         // Port inside the container

    const server = http.createServer((req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Hello from Docker!\n');
    });

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

  4. Create package.json (Node.js project configuration) in the my-docker-app directory:
    {
      "name": "my-docker-app",
      "version": "1.0.0",
      "description": "A simple Node.js app for Docker demonstration",
      "main": "app.js",
      "scripts": {
        "start": "node app.js"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
    }

Your project directory structure should now look like this:

my-docker-app/
├── Dockerfile
├── app.js
└── package.json

Step 2: Build the Docker Image

With your Dockerfile and application files in place, you can now build your Docker image. This process reads the Dockerfile instructions and creates a runnable image.

  1. Open your terminal or command prompt.

  2. Navigate to your project directory (my-docker-app):
    cd my-docker-app

  3. Run the Docker build command:
    docker build -t my-node-app .

  • docker build: The command to build a Docker image.

  • -t my-node-app: This tags your image with a human-readable name (my-node-app). It's good practice to use lowercase and descriptive names. You can also add a version tag (e.g., my-node-app:1.0).

  • .: This specifies the "build context" as the current directory. Docker will look for the Dockerfile in this location and send all files in this directory to the Docker daemon for the build process.

You will see output detailing each step as Docker executes the instructions in your Dockerfile. Upon successful completion, you'll see a message similar to:Successfully built <image_id>
Successfully tagged my-node-app:latest

  1. Verify the image was built:
    You can list all local Docker images to confirm your new image is present:
    docker images

    You should see my-node-app listed in the output.

Step 3: Run a Docker Container from the Image

Now that you have a Docker image, you can create and run a container from it. A container is a runnable instance of an image.

  1. Run the Docker container:
    docker run -p 4000:3000 my-node-app

  • docker run: The command to create and run a new container.

  • -p 4000:3000: This is crucial for accessing your application. It maps port 4000 on your host machine to port 3000 inside the Docker container. Your Node.js application is listening on port 3000 within the container (as defined by EXPOSE 3000 and app.js).

  • my-node-app: The name of the image you want to run.

Your terminal will now display the output from your Node.js application, similar to:Server running at http://0.0.0.0:3000/

This screen run example is with 8000 port !!

Step 4: Access Your Application

With the container running, open your web browser and navigate to:

http://localhost:4000

You should see the message: "Hello from Docker!"

Step 5: Stop and Remove Docker Resources (Optional)

Stopping a Running Container

  • If running in the foreground (as in Step 3): Go back to the terminal where the container is running and press Ctrl+C. This will stop the container.

  • If running in detached mode (background): For long-running applications, you'll often want to run the container in the background. You can do this by adding the -d (detached) flag:
    docker run -d -p 4000:3000 my-node-app

    To stop a detached container, you first need its container ID or name. List running containers:
    docker ps

    Note the CONTAINER ID (e.g., a1b2c3d4e5f6) or NAMES (e.g., vigilant_williams). Then stop it:
    docker stop <CONTAINER_ID_OR_NAME>

Removing Containers

Stopped containers still consume disk space. To remove a stopped container:

docker rm <CONTAINER_ID_OR_NAME>

You can also remove all stopped containers:

docker container prune

Removing Images

If you no longer need a Docker image, you can remove it to free up disk space:

docker rmi my-node-app

If the image is being used by a container, you'll need to stop and remove that container first.