Dockerizing a Node App
In this article I will be covering a basic understanding of how a Node.js application is structured assuming you have a working Docker installation. Please take the necessary steps to download Docker if you have not already.
Step 1: Initiate a new Node.Js App with NPM init
// package-lock.json
{
"name": "your_app_name",
"version": "2.0.0",
"description": "Your First Dockerized App",
"author": "Your Name",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.15.12"
}
}
Step 2: Run npm -i (AKA: npm install)
Step 3: Create Index.js file
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('What a wonderful World');
});
app.listen(3000, '0.0.0.0' () => {
console.log('Server listening on Port 3000');
});
Step 4: Create your Dockerfile: touch Dockerfile
#YOUR NODE VERSION
FROM node:15
# CREATE APP DIRECTORY
WORKDIR /app
# INSTALL APP DEPENDENCIES
COPY package*.json ./
# INSTALL DEPENDENCIES
RUN npm install
# BUNDLE APP
COPY . .
# DEFINE PORT
EXPOSE 3000
# RUN DOCKER APP
CMD [ "node", "index.js" ]
Step 5: Touch docker-compose.yml
version: '3.7' services:
web:
image: [Image-name]
build: .
command: node index.js
ports:
- "3000:3000"
volumes:
- ./[image-name]/app
- /app/node_modules
depends_on:
- mongodb
mongodb:
image: "mongo"
ports:
- "27017:27017"
Step 6: Touch .dockerignore
node_modules/
Step 7: Build Your Docker Container
docker build -t [App-name] .
Step 8: Run Docker Container
docker run -it -p 3000:3000 [App-name]
FINISH!!!