Bootstrap FreeKB - NodeJS - Getting Started with NodeJS Express on Docker
NodeJS - Getting Started with NodeJS Express on Docker

Updated:   |  NodeJS articles

Create a file named package.json that contains the following.

{
  "name": "NodeJS Express on Docker",
  "version": "1.0.0",
  "description": "",
  "main": "",
  "scripts": {
    "devStart": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.6",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.12"
  }
}

 

Create a file named server.js that contains the following route, console.log.

const express = require("express")
const app = express()

app.get('/', (req, res) => {
        console.log('Hello Console')
        res.send('Hello World')
})

app.listen(12345)

 

Create a file named Dockerfile that contains the following.

FROM node:18-alpine
WORKDIR /src
COPY package.json server.js /src/
RUN npm install --omit=dev
EXPOSE 12345
CMD ["npm", "start"]

 

You should now have the following files in your present working directory.

├── Dockerfile
├── package.json
├── server.js

 

On your Docker server, use the docker build command to create the NodeJS Express image.

sudo docker build --file Dockerfile --tag nodejs-express:18-alpine .

 

The docker images command should return something like this.

~]$ sudo docker images
REPOSITORY        TAG          IMAGE ID       CREATED         SIZE
nodejs-express    18-alpine    824127ec51d1   1 minute ago    189MB

 

The docker run command can be used to create and start a Docker container from the NodeJS Express image.

sudo docker run \
--name nodejs-express \
--publish 0.0.0.0:12345:12345 \
--detach \
nodejs-express:18-alpine

 

The docker container ls command should show the container is up and running.

~]$ sudo docker container ls
CONTAINER ID   IMAGE                      COMMAND                  CREATED        STATUS         PORTS                         NAMES
c19d5eab9a75   nodejs-express:18-alpine    "docker-entrypoint.s…"  1 minute ago   Up 1 minute    0.0.0.0:12345->12345/tcp   nodejs-express

 

The docker logs command should return something like this

]$ sudo docker logs nodejs-express
> NodeJS Express on Docker@1.0.0 start
> node server.js

 

Go to http://<your Docker servers hostname or IP address>:12345/ and the following should be displayed.

 

The docker logs command should now include "Hello Console".

]$ sudo docker logs nodejs-express
> NodeJS Express on Docker@1.0.0 start
> node server.js
Hello Console



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ff2034 in the box below so that we can be sure you are a human.