For this tutorial, I will assume you are starting a brand new Node.js application. If you already have a Node.js application you want to Dockerize, head over to Step 3.
*Before starting this tutorial, please make sure you have Docker downloaded.
Step 1
Initialize a new node.js app with
npm init
This will give you a package.json
file that looks something like this
// package-lock.json
{
"name": "sample_app",
"version": "1.0.0",
"description": "My First Dockerized Codebase",
"author": "Your Name",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "^4.17.1"
}
}
then run npm i
(previously npm install
) which will generate a package-lock.json
.
Step 2
Next, we will create an app.js
file
// app.js
const express = require('express');
const app = express();
const PORT = [Your-port-here];
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(PORT, '0.0.0.0' () => {
console.log('Server listening on Port ${PORT}');
});
Step 3
Here comes the fun part...
First, create a Dockerfile
touch Dockerfile
Inside the Dockerfile, you will need to define the following:
# you can find your node version with: node --version
FROM node:15
# Create app directory
WORKDIR /app
# Install app dependencies
COPY package*.json ./
# Install dependecies
RUN npm install
# Bundle app
COPY . .
# Define your port
EXPOSE 3000
# Tell Docker how to run your app
CMD [ "node", "app.js" ]
Step 4
Additional files are needed for Docker to successfully build your app.
.dockerignore
node_modules/
# anything else you want for Docker to ignore
docker-compose.yml
version: '3.7' # you can find yours with python --version
services:
web:
image: [your-image-name]
build: .
command: node app.js
ports:
- "4040:4040"
volumes:
- ./[your-image-name]/app
- /app/node_modules
depends_on:
- mongodb
mongodb:
image: "mongo"
ports:
- "27017:27017"
Step 5
Now that we have all the files, we can build and run the container.
Build a Docker container
docker build -t [your-app-name] .
Run the Docker container
docker run -it -p 3000:3000 [your-app-name]
Congratulations π₯³
If you have made it this far, you have successfully Dockerized your Node.js app.
Addition Docker Commands
docker ps
Check for running containers
docker-compose run [app-name] npm run migrate
Run migration and create table
docker pull
Pulls an image or a repository from a registry
Top comments (2)
Recently somebody posted Docker Best Practices on dev.to. There are many usefull things.
Indeed it has lots of useful information. Thanks for the comment!