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

104 lines
2.2 KiB
Markdown
Raw Normal View History

2023-06-28 19:51:45 +00:00
---
title: Running a NodeJS application in Docker
description: Guide for running a NodeJS application in Docker
published: true
date: 2023-06-28T20:38:30.081Z
tags: nodejs, docker
editor: markdown
dateCreated: 2023-06-28T20:38:59.640Z
---
# Running a NodeJS application in Docker
We will be using the guide [Creating a Simple REST API](/guides/nodejs/pages/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:
```dockerfile
FROM node:latest
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]
```
3. Now we can move on to the `docker-compose.yml` file. We need to create a new file called `docker-compose.yml`.
4. Next, we need to open the `docker-compose.yml` file and add the following code:
```yaml
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.
5. You can now copyy the project files to where you want to run the application.
6. Next, we need to open the terminal and run the following command:
```bash
docker-compose up -d
```
This will start the application in the background.
7. 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:
```bash
docker-compose down
```
This will stop the application.
2. Next, we need to update the application files. You can do this by copying the updated files to the server.
3. Next, we need to open the terminal and run the following command:
```bash
docker-compose build
```
This will re-build the Docker image.
4. Next, we need to open the terminal and run the following command:
```bash
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.