How To Dockerize A Node - Js Application With Docker and Docker Compose
How To Dockerize A Node - Js Application With Docker and Docker Compose
This tutorial will guide you through containerizing a basic Node.js application
using Docker. We’ll also set up Docker Compose to streamline development and
deployment.
---
### Prerequisites
---
```bash
mkdir docker_node_app
cd docker_node_app
```
```bash
npm init -y
npm install express
```
3. Create an `app.js` file in the root of the project directory with a simple
server configuration.
```javascript
// app.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
```
---
In the root of your project directory, create a file named `Dockerfile` to define
how the application will be built and run inside the Docker container.
```dockerfile
# Dockerfile
# Step 1: Use the official Node.js image as the base image
FROM node:14
---
Add a `.dockerignore` file to specify files and directories that should be excluded
from the Docker image.
```plaintext
node_modules
npm-debug.log
```
---
In the terminal, run the following command to build the Docker image for the
application.
```bash
docker build -t docker-node-app .
```
Here:
- `docker build` initiates the Docker image build process.
- `-t docker-node-app` tags the image with the name `docker-node-app`.
- `.` specifies the build context (current directory).
---
To run the Docker container from the image you just created:
```bash
docker run -p 3000:3000 docker-node-app
```
This maps port 3000 of the container to port 3000 on your local machine. You can
now access the application at `http://localhost:3000`.
---
```yaml
# docker-compose.yml
version: '3'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- PORT=3000
```
```bash
docker-compose up
```
This command will build and run the application in a container based on the
`docker-compose.yml` configuration.
---
With Docker Compose running, you should be able to access the application by going
to `http://localhost:3000` in your browser. You should see the message:
```
Hello, Dockerized World!
```
To stop the application, press `CTRL+C`, and then bring down the container network
using:
```bash
docker-compose down
```
---
To run the containers in the background (detached mode), add the `-d` flag:
```bash
docker-compose up -d
```
```bash
docker-compose down
```
---
### Conclusion
---