Bootstrap FreeKB - Node.js - Getting Started with Client Server Express on Docker
Node.js - Getting Started with Client Server Express on Docker

Updated:   |  Node.js articles

Assuming you are on a Linux system, let's create a temp directory.

mkdir /tmp/client_server

 

And move into the temp directory.

cd /tmp/client_server

 

Use the npm init command to create package.json.

npm init -y

 

Let's update package.json to have "type": "module" since this will be an ES Module.

Let's also add "dependencies": { "express": "^<version>" } so that Express get installed in the Docker image.

{
  "type": "module",
  "name": "bar",
  "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
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

 

Now let's create two apps, the Node.js client app that will connect to the Node.js server app.

 

Create /tmp/server.js that contains the following.

import net from "net";
import os from "os";

const server = net.createServer();
const timestamp = () => `[${new Date().toUTCString()}]`
const port = 22222
const host = os.hostname();

server.on("connection", (socket) => {
    console.log(`${timestamp()} successfully connected to server.js`)
})

server.listen(port, host, () => {
    console.log(`${timestamp()} server listening for connections at ${host}:${port}`);
})

 

The docker run command can be used to create and start a Docker container from the Node.js Express image with server.js and then use the node server.js command to run server.js.

sudo docker run \
--name nodejs-server \
--publish 0.0.0.0:22222:22222 \
--detach \
--volume /tmp/server.js:/src/server.js \
nodejs-express:18-alpine \
node server.js

 

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

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

 

The docker logs command should return something like this.

~]$ sudo docker logs nodejs-server
[Sun, 01 Sep 2024 12:47:57 GMT] server listening for connections at e901cdaafafa:22222

 

Let's create /tmp/client.js with the following markup using the hostname of the Docker host. In this example, the Docker host is running on an Amazon Web Services (AWS) server with hostname ec2-11-12-13-14.compute-1.amazonaws.com.

import net from "net";

import express from "express";

const timestamp = () => `[${new Date().toUTCString()}]`
const server_port = 22222
const client_port = 11111
const host = "ec2-11-12-13-14.compute-1.amazonaws.com";
const app = express()

app.get('/', (req, res) => {
  console.log(`${timestamp()} Hello Console`)
  net.createConnection({host: host, port: server_port},() => {
      console.log(`${timestamp()} successfully connected to server.js`);
  })
  res.send(`${timestamp()} Hello Browser`)
})

app.listen(client_port)
console.log(`${timestamp()} Node.js client is up and listening for connections at ${host}:${client_port}`);

 

The docker run command can be used to create and start a Docker container from the Node.js Express image with client.js and then use the node client.js command to run client.js.

sudo docker run \
--name nodejs-client \
--publish 0.0.0.0:11111:11111 \
--detach \
--volume /tmp/client.js:/src/client.js \
nodejs-express:18-alpine \
node client.js

 

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
e901cdaafafa   nodejs-express:18-alpine     "docker-entrypoint.s…"   4 seconds ago   Up 3 seconds    12345/tcp         nodejs-clinet

 

The docker logs command should return something like this.

~]$ sudo docker logs nodejs-client
Node.js client is up and running and listening for connections at ec2-11-12-13-14.compute-1.amazonaws.com:11111

 

In this example, my Docker host is running on an Amazon Web Services (AWS) EC2 instance, so I update the Security Group associated with the EC2 instance to allow inbound connections on the port being used by the client, 11111 in this example.

aws ec2 authorize-security-group-ingress --group-id sg-123456789abcdefg --protocol tcp --port 11111 --cidr 0.0.0.0/0

 

Let's go to the host and port defined in the client and Hello Browser should be displayed. Nice!

 

And the docker logs command should return something like this. Sweet!

~]$ sudo docker logs nodejs-client
Node.js client is up and listening for connections at ec2-11-12-13-14.compute-1.amazonaws.com:11111
[Mon, 02 Sep 2024 11:41:10 GMT] Hello Console
[Mon, 02 Sep 2024 11:41:10 GMT] successfully connected to server.js

 




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 facbb7 in the box below so that we can be sure you are a human.