docs/guides/nodejs/pages/running-nodejs-in-docker.md

2.2 KiB

title description published date tags editor dateCreated
Running a NodeJS application in Docker Guide for running a NodeJS application in Docker true 2023-06-28T20:38:30.081Z nodejs, docker markdown 2023-06-28T20:38:59.640Z

Running a NodeJS application in Docker

We will be using the guide Creating a Simple REST API as the example application.

Prerequisites

  • Docker installed
  • Docker Compose installed

Get Started

  1. First we need to create a new file called Dockerfile.

  2. Next, we need to open the Dockerfile file and add the following code:

FROM node:latest

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD ["node", "index.js"]
  1. Now we can move on to the docker-compose.yml file. We need to create a new file called docker-compose.yml.

  2. Next, we need to open the docker-compose.yml file and add the following code:

version: "3.9"

services:
  nodejs_rest_api:
    build: .
    restart: unless-stopped
    ports:
      - "3000:3000"

This will create a new service called nodejs_rest_api and build the Docker image using the Dockerfile in the current directory.

  1. You can now copyy the project files to where you want to run the application.

  2. Next, we need to open the terminal and run the following command:

docker-compose up -d

This will start the application in the background.

  1. Next, we need to open a web browser and navigate to http://server_ip:3000.

You should now see your application running.

Updating the application

  1. First we need to open the terminal and run the following command:
docker-compose down

This will stop the application.

  1. Next, we need to update the application files. You can do this by copying the updated files to the server.

  2. Next, we need to open the terminal and run the following command:

docker-compose build

This will re-build the Docker image.

  1. Next, we need to open the terminal and run the following command:
docker-compose up -d

This will start the application in the background again.

Finished

You have now successfully created a NodeJS application and run it in Docker and know how to update it.