
Assuming you are on a Linux system, let's create a temp directory.
mkdir /tmp/express
And move into the temp directory.
cd /tmp/express
Use the npm init command to create package.json.
npm init -y
Use npm install to install the express module.
npm install express
package.json should have the following.
{
"name": "express-docker",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.19.2"
}
}
Create a file named Dockerfile that contains the following.
FROM node:18-alpine
WORKDIR /src
COPY . .
RUN npm install
CMD [ "node", "index.js" ]
EXPOSE 12345
You should now have the following files in your present working directory.
├── Dockerfile
├── package.json
On your Docker server, use the docker build command to create the Node.js 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
Create /tmp/index.js that contains the following.
const express = require("express")
const app = express()
const timestamp = () => Date()
app.get('/', (req, res) => {
console.log(`${timestamp()} Hello Console`)
res.send(`${timestamp()} Hello World`)
})
app.listen(12345)
console.log(`Node.js app is up and running!`);
The docker run command can be used to create and start a Docker container from the Node.js Express image with index.js.
sudo docker run \
--name nodejs-express \
--publish 0.0.0.0:12345:12345 \
--detach \
--volume /tmp/index.js:/src/index.js \
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 app is up and running!
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 app is up and running!
Fri Jul 05 2024 00:06:35 GMT+0000 (Coordinated Universal Time) Hello Console
Did you find this article helpful?
If so, consider buying me a coffee over at