0% found this document useful (0 votes)
17 views9 pages

Lab 9

The document outlines a lab assignment for ICS-423 on creating two services using Golang and Node.js within Docker containers. Service A generates a random number, while Service B consumes this number and doubles it. The document includes detailed steps, code snippets, and Docker configurations for both implementations.

Uploaded by

jobsanish5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views9 pages

Lab 9

The document outlines a lab assignment for ICS-423 on creating two services using Golang and Node.js within Docker containers. Service A generates a random number, while Service B consumes this number and doubles it. The document includes detailed steps, code snippets, and Docker configurations for both implementations.

Uploaded by

jobsanish5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

ICS-423 Internet of Things

Lab-9

Name: Kanak Khandelwal


Roll No.: 2021BCS0102
Task-1: Write golang-based services (2 numbers) on docker containers.

Algorithm:

1. Prepare two folders for serviceA and serviceB.


2. Here we will create two services, service A and service B.
3. Service A: Provides a random number.
4. Service B: Consumes the number from Service A and doubles it.
5. Write the codes for both the services and create dockerfiles mentioning nodejs
as the image to use.
6. Also create package.json files for the installation of necessary libraries.
7. Create a docker-compose file to run and manage both the containers
simultaneously.
8. Build the image using docker-compose build.
9. Start the containers using docker-compose up.

Output:

1. Running service A

2. Running service B
Code:

Service A

main.go

package main

import (
"encoding/json"
"math/rand"
"net/http"
"time"
"log"
)

type NumberResponse struct {


Number int `json:"number"`
}

func generateRandomNumber(w http.ResponseWriter, r *http.Request) {


rand.Seed(time.Now().UnixNano())
number := rand.Intn(100)
response := NumberResponse{Number: number}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}

func main() {
http.HandleFunc("/number", generateRandomNumber)
port := ":3000"
log.Printf("Service A running on port %s", port)
log.Fatal(http.ListenAndServe(port, nil))
}

Go.mod

module servicea

go 1.20
Dockerfile

FROM golang:1.20

WORKDIR /app

COPY go.mod ./

RUN go mod tidy

COPY . .

RUN go build -o servicea main.go

EXPOSE 3000

CMD ["./servicea"]

Sevice B

Main.go

package main

import (
"encoding/json"
"log"
"net/http"
)

type NumberResponse struct {


Number int `json:"number"`
}

type DoubledResponse struct {


Doubled int `json:"doubled"`
}

func doubleNumber(w http.ResponseWriter, r *http.Request) {


resp, err := http.Get("http://servicea:3000/number")
if err != nil {
http.Error(w, "Failed to fetch number from Service A", http.StatusInternalServerError)
return
}
defer resp.Body.Close()

var numberResp NumberResponse


if err := json.NewDecoder(resp.Body).Decode(&numberResp); err != nil {
http.Error(w, "Failed to decode response", http.StatusInternalServerError)
return
}

response := DoubledResponse{Doubled: numberResp.Number * 2}


w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func main() {
http.HandleFunc("/double", doubleNumber)
port := ":4000"
log.Printf("Service B running on port %s", port)
log.Fatal(http.ListenAndServe(port, nil))
}

Go.mod

module serviceb

go 1.20

Dockerfile

FROM golang:1.20

WORKDIR /app

COPY go.mod ./
RUN go mod tidy

COPY . .

RUN go build -o serviceb main.go

EXPOSE 4000

CMD ["./serviceb"]

Task-2: Write nodejs-based services (2 numbers) on docker containers.

Algorithm:

1. Prepare two folders for serviceA and serviceB.


2. Here we will create two services, service A and service B.
3. Service A: Provides a random number.
4. Service B: Consumes the number from Service A and doubles it.
5. Write the codes for both the services and create dockerfiles mentioning nodejs as
the image to use.
6. Also create package.json files for the installation of necessary libraries.
7. Create a docker-compose file to run and manage both the containers
simultaneously.
8. Build the image using docker-compose build.
9. Start the containers using docker-compose up.

Output:

3. Running service A
4. Running service B

Code:

Server A

Server.js

const express = require('express');


const app = express();
const PORT = 3000;

app.get('/number', (req, res) => {


const randomNumber = Math.floor(Math.random() * 100);
res.json({ number: randomNumber });
});

app.listen(PORT, () => {
console.log(`Service A running on port ${PORT}`);
});

Package.json

{
"name": "service-a",
"version": "1.0.0",
"main": "server.js",
"dependencies": {
"express": "^4.18.2"
}
}

Dockerfile

FROM node:18

# Working directory
WORKDIR /app

COPY package.json ./
RUN npm install

COPY . .

# Expose port
EXPOSE 3000

CMD ["node", "server.js"]

Server B

Server.js

const express = require('express');


const axios = require('axios');

const app = express();


const PORT = 4000;

app.get('/double', async (req, res) => {


try {
const response = await axios.get('http://serviceA:3000/number');
const number = response.data.number;
res.json({ doubled: number * 2 });
} catch (error) {
res.status(500).json({ error: "Failed to fetch number from Service A" });
}
});

app.listen(PORT, () => {
console.log(`Service B running on port ${PORT}`);
});

Package.json

{
"name": "service-b",
"version": "1.0.0",
"main": "server.js",
"dependencies": {
"express": "^4.18.2",
"axios": "^1.4.0"
}
}

Dockerfile

FROM node:18

# Working directory
WORKDIR /app

COPY package.json ./
RUN npm install

COPY . .

# Expose port
EXPOSE 4000

CMD ["node", "server.js"]

You might also like