0% found this document useful (0 votes)
9 views

Microservices_Batch_2022_solved

Microservices
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)
9 views

Microservices_Batch_2022_solved

Microservices
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/ 32

SVKM's NMIMS

MUKESH PATEL SCHOOL OF TECHNOLOGY


MANAGEMENT & N
SCHOOL OF TECHNOLOGY MANAGEMENT &
ENGINEE
Academic Year: 2022-23

Programme: MCA Year: 11 Semester: Ill

Subject: Microservices Software Architecture


Marks: 100
Date: 17 November 2022 Time: 10.00 am - 1.00 pm

What are Microservices? What are the main differences 5


between Microservices and SOA Architecture?
Ans:
• Microservices is a small, loosely coupled distributed
services.
• Each microservices design to perform single business
function and is can be developed, deployed and
scalable independently.
• A Service-Oriented Architecture or SOA is a design
pattern which is used to design distributed system
that delivers services to other applications through
the protocol.
• It is only concept not limited to any programming
language or platform.

Aspect SOA Microservices

Implementation Different Independent


services with and purpose-
shared resources specific
smaller
services
Communication ESB (Enterprise API
Service Bus) (Application
Programme
Interface)
Data Storage Shared Data Independent
Storage Data Storage
Deployment Challenging a full Easy to deploy
rebuild required each service
for small changes. can be
containerized.
Reusability Reusable through Each service
shared common has its own
resources. resource and
it can
reusable
through their
APIs.
Speed Slows down as more Consistent
services are added speed as
on. traffic is
grown.
Coupling Resource Bounded
sharing/loose context
coupling
Architecture Services areServices are
reused and shared decoupled and
at the enterprise operate
level independently
Granularity Relatively large, Smaller more
modular services flexible
services
Governance Consistent data Different
flexibility governance across governance
all services. policies for
each storage.
Difference between Spring and Spring Boot? 5
Ans:
Aspect Spring Framework Spring Boot
Definition Spring Framework Spring boot is
is an open-source built on top of
java platform spring. It
that provides simplifies
comprehensive spring
infrastructure application
for developing bootstrapping
java by providing
automatic
configuration
and runtime
simplicity
Configu. Spring requires a Uses auto-
lot of configuration
configuration.You and provides
have to setup opinionated
everything by defaults to
yourself reduce setup
and boilerplate
code
Project setup Initial project Comes with
setup can be spring
cumbersome and initializer for
might involve quick project
boilerplate code bootstrapping.
Web servers Requires external Comes with
server like internal
tomcat, jetty for server(tomcat ,
deployment. jetty)that
enable
standalone
application.
Deployment Generates WAR/EAR Typically
files typically generates
deployed to standalone JAR
external for embedded
application server for
servers simplified
deployment.
Microservices Requires manual Easily
setup and integrated with
integration with spring cloud.
other tools for Making
microservices microservices
development
more
straightforward
Production- Requires Built-in
ready features additional tools actuator module
and configuration provides
for monitoring monitoring
metrics and
health checks health checks,
etc. etc.
Properties Property source Provides
setup and uniform
hierarchy must be property source
configured with sensible
manually. defaults and
environment
specific
configuration.
Testing Requires Provides built-
additional in
configuration and configuration
setup for with
integration @SpringBootTest
testing.
Learning curve Deep learning Easier for
required due to beginners due
need to to its
understand and convention-
configure each over-
module seperately configuration
approach

Write a note on Synchronous and Asynchronous 5


communication in Microservices.
Ans: Client and services can communicate with many
different types of communication mainly classified into
two types.
Synchronous Communication:
• In Synchronous communication model client sends a
request and waits for the response from the service.
So that means client cannot proceed next request
until previous response is received.
• Synchronous Communication uses HTTP gRPC protocol
for returning synchronous response from the service.
Asynchronous Communication:
• In Asynchronous communication, client sends a
request but it doesn’t wait for the response from
the service.
• So the key point here is that, the client should not
blocked a thread while waiting for a response.
• The most popular protocol for this Asynchronous
Communications is AMQP (Advanced Message Queuing
Protocol).
• So with using AMQP protocols, the client sends the
message with using message broker systems like Kafka
and RabbitMQ queue.

Write a note on Spring Boot Actuator 5


Ans:
Spring Boot Actuator is a powerful feature in spring boot
framework that provides production-ready tools to
monitor, manage, and interact with your application.
It enables developers to gain insights into applications
health, metrics, and performance as well as perform
operational task.
Key Features of Spring Boot Actuator
1. Predefined Endpoints
Actuator provides a variety of endpoints to monitor
and manage the application, such as:
o /actuator/health: Reports the application's
health status (e.g., UP or DOWN).
o /actuator/metrics: Displays various metrics like
memory usage, garbage collection, and thread
pool statistics.
o /actuator/info: Exposes custom application-
specific information (e.g., version,
description).
o /actuator/env: Shows the environment properties.
o /actuator/httptrace: Displays details of recent
HTTP requests (requires additional
configuration).
2. Customizable Endpoints
o You can enable or disable specific endpoints.
o Custom endpoints can be created to expose
application-specific monitoring and management
data.
3. Integration with Monitoring Tools
o Supports integration with tools like Prometheus,
Grafana, and ELK Stack through metrics and logs.
o Provides compatibility with Micrometer for
flexible metrics publishing.

What is a distributed transaction? Two-phase commit 10


(2pc) pattern. What are the benefits disadvantages of
using 2pc?
Ans:
• In Microservices Architecture, a distributed
transaction spans multiple services, where each
service may have its own databases or external
resources.
• Ensuring data consistency across this distributed
services during a single operation is challenging
due to their distributed nature
Example:
In an e-commerce system, placing an order might
involve:
1. Deducting inventory in the inventory service.
2. Charging the customer in the payment service.
3. Creating an order record in the order service.
These actions need to be consistent, even though
they occur in different services.
Two-Phase Commit (2PC) Pattern in Microservices
Two-Phase Commit (2PC) is a protocol used to manage
distributed transactions and ensure atomicity across
multiple services.
How 2PC Works in Microservices
1. Coordinator Service:
A service acts as the coordinator to manage the
transaction, often implemented with a transaction
manager.
2. Phase 1: Prepare Phase
o The coordinator sends a "prepare" request to
all participating services.
o Each service:
▪ Validates the request.
▪ Prepares for the transaction by locking
resources or setting up transaction logs.
▪ Responds "yes" (ready to commit) or "no"
(abort).
3. Phase 2: Commit/Rollback Phase
o If all services respond "yes":
▪ The coordinator sends a "commit" command.
▪ Each service completes the operation and
releases locks.
o If any service responds "no" or a failure
occurs:
▪ The coordinator sends a "rollback" command.
▪ Each service reverts its changes.
Benefits of Using 2PC in Microservices:
1. Strong Consistency:
Ensures all services maintain consistent data by
committing or rolling back together.
2. Simplicity in Usage:
Developers do not need to implement custom rollback
mechanisms for each service.
3. Transparency:
Participants follow the protocol, and the
transaction manager handles coordination, reducing
developer overhead.
4. Reliability:
Provides clear recovery mechanisms through
transaction logs, even during failures.

Disadvantages of Using 2PC in Microservices


1. Performance Overhead:
o Involves multiple network calls between the
coordinator and services.
o Services hold locks on resources, which can
degrade system performance.
2. Blocking Nature:
o Locks held during the prepare phase block other
transactions, impacting throughput.
3. Single Point of Failure:
o The coordinator is a critical component; its
failure can disrupt the transaction and require
complex recovery.
4. Reduced Scalability:
o As the number of services increases,
coordination overhead and communication latency
grow, limiting scalability.
5. Complexity in Distributed Environments:
o Network failures, service timeouts, and
partitioning can make 2PC challenging to
implement in a highly distributed setup.

Write a code demonstrating CRUD operation in 10


Microservices.
Ans:
1. Employee Service (CRUD Microservice)
Project Structure

employee-service
├── src/main/java/com/example/employeeservice
│ ├── EmployeeServiceApplication.java
│ ├── controller
│ │ └── EmployeeController.java
│ ├── model
│ │ └── Employee.java
│ ├── repository
│ │ └── EmployeeRepository.java
│ ├── service
│ └── EmployeeService.java
├── src/main/resources
│ └── application.properties

1.1. EmployeeServiceApplication.java

package com.example.employeeservice;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplicat
ion;
@SpringBootApplication
public class EmployeeServiceApplication {
public static void main(String[] args) {

SpringApplication.run(EmployeeServiceApplication.class,
args);
}
}

1.2. Model: Employee.java

package com.example.employeeservice.model;

import jakarta.persistence.*;

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;


private String department;
private Double salary;

// Getters and Setters


public Long getId() {
return id;
}

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
public String getDepartment() {
return department;
}

public void setDepartment(String department) {


this.department = department;
}

public Double getSalary() {


return salary;
}

public void setSalary(Double salary) {


this.salary = salary;
}
}

1.3. Repository: EmployeeRepository.java

package com.example.employeeservice.repository;

import com.example.employeeservice.model.Employee;
import
org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends
JpaRepository<Employee, Long> {
}

1.4. Service: EmployeeService.java

package com.example.employeeservice.service;

import com.example.employeeservice.model.Employee;
import
com.example.employeeservice.repository.EmployeeRepository
;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class EmployeeService {

@Autowired
private EmployeeRepository repository;

public Employee createEmployee(Employee employee) {


return repository.save(employee);
}

public List<Employee> getAllEmployees() {


return repository.findAll();
}

public Optional<Employee> getEmployeeById(Long id) {


return repository.findById(id);
}

public Employee updateEmployee(Long id, Employee


updatedEmployee) {
return repository.findById(id).map(employee -> {
employee.setName(updatedEmployee.getName());

employee.setDepartment(updatedEmployee.getDepartment());

employee.setSalary(updatedEmployee.getSalary());
return repository.save(employee);
}).orElseThrow(() -> new
RuntimeException("Employee not found"));
}

public void deleteEmployee(Long id) {


repository.deleteById(id);
}
}

1.5. Controller: EmployeeController.java


package com.example.employeeservice.controller;

import com.example.employeeservice.model.Employee;
import
com.example.employeeservice.service.EmployeeService;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employees")
public class EmployeeController {

@Autowired
private EmployeeService service;

@PostMapping
public ResponseEntity<Employee>
createEmployee(@RequestBody Employee employee) {
return
ResponseEntity.ok(service.createEmployee(employee));
}

@GetMapping
public ResponseEntity<List<Employee>>
getAllEmployees() {
return
ResponseEntity.ok(service.getAllEmployees());
}

@GetMapping("/{id}")
public ResponseEntity<Employee>
getEmployeeById(@PathVariable Long id) {
return service.getEmployeeById(id)
.map(ResponseEntity::ok)

.orElse(ResponseEntity.notFound().build());
}

@PutMapping("/{id}")
public ResponseEntity<Employee>
updateEmployee(@PathVariable Long id, @RequestBody
Employee employee) {
return
ResponseEntity.ok(service.updateEmployee(id, employee));
}

@DeleteMapping("/{id}")
public ResponseEntity<Void>
deleteEmployee(@PathVariable Long id) {
service.deleteEmployee(id);
return ResponseEntity.noContent().build();
}
}

1.6. Configuration: application.properties


Application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/employe
e_db
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
server.port=8081

Running the Microservice


1. Database Setup: Create a database named employee_db
in MySQL (or update the configuration for another
database).
2. Start the Service: Run the application using mvn
spring-boot:run or through an IDE like IntelliJ or
Eclipse.
3. Test Endpoints: Use tools like Postman or cURL to
interact with the endpoints:
o POST /employees: Create a new employee.
o GET /employees: Retrieve all employees.
o GET /employees/{id}: Get a specific employee.
o PUT /employees/{id}: Update an employee.
o DELETE /employees/{id}: Delete an employee.
Explain API Gateway Architecture? What are the advantages 10
and drawbacks?
Ans:
An API Gateway is a server or software layer that sits
between client applications and backend microservices. It
acts as a single entry point for all client requests,
providing routing, security, rate-limiting, logging, and
other functionalities.
How It Works
1. Client Request: Clients (e.g., web apps, mobile
apps) send requests to the API Gateway instead of
directly communicating with microservices.
2. Routing: The gateway routes requests to the
appropriate microservice.
3. Aggregation: For composite requests, the API Gateway
can aggregate responses from multiple microservices
and send a unified response to the client.
4. Additional Features: The gateway can also handle
cross-cutting concerns like authentication, logging,
caching, load balancing, and throttling.

Advantages of API Gateway Architecture


1. Simplified Client Communication:
o Clients interact with a single entry point,
hiding the complexity of multiple services.
2. Centralized Cross-Cutting Concerns:
o Authentication, rate-limiting, and monitoring
can be managed in one place.
3. Improved Security:
o The gateway acts as a security barrier,
protecting internal microservices from direct
exposure to clients.
4. Optimized Performance:
o Enables response aggregation and caching,
reducing latency and improving efficiency.
5. Scalability:
o Offloads client-specific concerns from
microservices, allowing them to focus on
business logic.
6. Protocol Flexibility:
o Facilitates protocol translation, enabling
legacy systems to work with modern applications.
7. Simplified Microservice Changes:
o Changes to microservice APIs can be abstracted
by the gateway, minimizing client impact.

Drawbacks of API Gateway Architecture


1. Single Point of Failure:
o The gateway becomes a critical dependency; if it
goes down, the entire system becomes
inaccessible.
Solution: Use redundancy and deploy the gateway
in a highly available configuration.
2. Increased Latency:
o Adds an additional network hop between the
client and backend services, which could
introduce latency.
Solution: Optimize caching and reduce
unnecessary processing in the gateway.
3. Complexity:
o Adds another component to the architecture,
increasing deployment and maintenance
complexity.
Solution: Leverage managed API gateway solutions
(e.g., AWS API Gateway, Kong).
4. Scalability Bottleneck:
o If not properly scaled, the gateway can become a
bottleneck for high-volume traffic.
Solution: Implement load balancing and
horizontal scaling for the gateway.
5. Development Overhead:
o Requires careful design to support routing,
aggregation, and other features, which can slow
down initial development.
Solution: Adopt existing frameworks (e.g.,
Spring Cloud Gateway) or API Gateway services.

Popular API Gateway Tools


1. Managed Solutions:
o AWS API Gateway
o Azure API Management
o Google Cloud Endpoints
2. Open-Source Tools:
o Kong
o NGINX
o Traefik
o Spring Cloud Gateway

How to Implement Microservice Registry using Eureka 10


Client and Server. Write the configuration needed?
Ans:
Step 1: Create a Combined Project with Spring
Initializer
1. Go to Spring Initializer:
o Project: Maven
o Language: Java
o Spring Boot: Latest version (e.g., 3.x)
o Dependencies:
▪ Spring Boot DevTools
▪ Spring Web
▪ Eureka Server
▪ Eureka Client
2. Generate the Project:
o Click "Generate" to download the project.
o Extract the ZIP file and open it in your IDE.
Step 2: Configure Eureka Server
1. Open the main application class and enable Eureka
Server.
EurekaApplication.java

package com.example.eureka;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplica
tion;
import
org.springframework.cloud.netflix.eureka.server.EnableEu
rekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class,
args);
}
}

2. Add application.properties configurations for the


Eureka Server:
application.properties
server.port=8761
spring.application.name=eureka-server

# Disable self-registration for the server


eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

# Enable the Eureka dashboard


eureka.server.enable-self-preservation=false

Step 3: Configure Eureka Client


1. Add a client controller to simulate a microservice
registering with Eureka.
HelloController.java

package com.example.eureka;

import
org.springframework.web.bind.annotation.GetMapping;
import
org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello from Eureka Client!";
}
}

2. Update the application.properties to include both


client and server configurations:
application.properties

# Common Server Configurations


server.port=8761
spring.application.name=eureka-server

# Eureka Server
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

# Eureka Client
eureka.client.service-
url.defaultZone=http://localhost:8761/eureka/
spring.application.name=eureka-client

Step 3: Configure Eureka Client


1. Add a client controller to simulate a microservice
registering with Eureka.
HelloController.java

package com.example.eureka;

import
org.springframework.web.bind.annotation.GetMapping;
import
org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello from Eureka Client!";
}
}

2. Update the application.properties to include both


client and server configurations:
application.properties

# Common Server Configurations


server.port=8761
spring.application.name=eureka-server

# Eureka Server
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

# Eureka Client
eureka.client.service-
url.defaultZone=http://localhost:8761/eureka/
spring.application.name=eureka-client

What is Spring Data JPA? Write the code using h2 10


database?
Ans:
• Spring boot JPA is a java specification for managing
relational data in java applications.
• It allows us to access or persist data between java
class/object and relational database.
• JPA follows Object Relational Mapping (ORM),it is a
set of interfaces.
• With Spring Data JPA, you can work with databases
using repository interfaces rather than writing
complex SQL queries.
Features:
1. Supports repositories like CrudRepository,
JpaRepository.
2. Automatic query generation from method names.
3. Integration with relational databases via JPA.
4. Simplifies interaction with the database.
5. Works seamlessly with Spring Boot.
Spring Data JPA with H2 Database
Below is a complete example using Spring Data JPA with an
in-memory H2 database.

Step 1: Set Up Spring Boot Project


1. Go to Spring Initializer:
Spring Initializer
2. Project Configuration:
o Project: Maven
o Language: Java
o Spring Boot: Latest version (e.g., 3.x)
o Dependencies:
▪ Spring Data JPA
▪ Spring Web
▪ H2 Database
▪ Spring Boot DevTools
3. Generate the Project:
o Click "Generate" to download the project.
o Extract the ZIP file and open it in your IDE.

Step 2: Create a JPA Entity


Create a class to represent the database table.
User.java

package com.example.springdatajpa.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;

// Constructors
public User() {}

public User(String name, String email) {


this.name = name;
this.email = email;
}

// Getters and Setters


public Long getId() {
return id;
}

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}
}

Step 3: Create a Spring Data JPA Repository


UserRepository.java

package com.example.springdatajpa.repository;

import com.example.springdatajpa.entity.User;
import
org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends
JpaRepository<User, Long> {
// Custom query methods (optional)
User findByEmail(String email);
}

Step 4: Create a REST Controller


UserController.java
package com.example.springdatajpa.controller;

import com.example.springdatajpa.entity.User;
import
com.example.springdatajpa.repository.UserRepository;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

@Autowired
private UserRepository userRepository;

// Create a new user


@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}

// Get all users


@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}

// Get user by ID
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userRepository.findById(id).orElse(null);
}

// Update user
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id,
@RequestBody User userDetails) {
User user =
userRepository.findById(id).orElse(null);
if (user != null) {
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
return userRepository.save(user);
}
return null;
}

// Delete user
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
}
}

Step 5: Configure H2 Database


Add the following to the application.properties file:
properties
Copy code
# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-
platform=org.hibernate.dialect.H2Dialect

# Enable H2 console
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

# Show SQL statements


spring.jpa.show-sql=true

Step 6: Run the Application


1. Start the Application:
o Run the main class
(SpringDataJpaApplication.java).
2. Access H2 Console:
o Open the H2 console at http://localhost:8080/h2-
console.
o Use the JDBC URL: jdbc:h2:mem:testdb, username:
sa, and password: password.
3. Test the REST API:
o Use tools like Postman or cURL to interact with
the API.
o Example endpoints:
▪ POST /users - Create a user.
▪ GET /users - Fetch all users.
▪ GET /users/{id} - Fetch a user by ID.
▪ PUT /users/{id} - Update a user.
▪ DELETE /users/{id} - Delete a user.

Design pattern in Spring Microservices with diagram. 10


Ans:
1. API Gateway Patterns in Microservices
In the Microservices Architecture, the API
Gateway patterns stand out as a crucial architectural
tool. They act as a central hub, managing and optimizing
communication between clients and multiple microservices.
These patterns simplify complexity, enhance security, and
improve performance, making them indispensable for
building scalable and resilient systems.

2. Service Discovery Pattern


• Description:
o Services dynamically register themselves with a
Service Registry (e.g., Eureka) to enable
location transparency. Other services query the
registry to find available service instances.
• Tools: Spring Cloud Eureka.
3. Database per Service Pattern
• Description:
o Each microservice has its own dedicated database
to ensure data encapsulation and avoid tight
coupling.
• Tools: Spring Data JPA, Spring Cloud Stream (for
event-driven consistency).

4. Centralized Configuration Pattern


• Description:
o Provides a single source of truth for service
configurations. Centralized configuration
enables dynamic updates and avoids hardcoding.
• Tools: Spring Cloud Config Server.
5. Sidecar Pattern
• Description:
o A helper application runs alongside the main
service to handle auxiliary tasks like
monitoring or logging.
• Tools: Spring Boot Admin, Micrometer.

Why use Docker? Explain the Docker Architecture? Write 5 10


Docker commands.
Ans:
Why Use Docker in Microservices?
Docker is a containerization tool that provides
lightweight, portable, and consistent environments for
deploying microservices. Here's why it is particularly
suited for microservices:
1. Isolation:
Each microservice runs in its container, ensuring
that dependencies and configurations are isolated
from others.
2. Portability:
Containers can run on any platform with Docker
installed, making deployments consistent across
development, testing, and production environments.
3. Scalability:
Docker makes it easy to scale services horizontally
by running multiple instances of a container.
4. Rapid Deployment:
With pre-built Docker images, microservices can be
deployed quickly and efficiently.
5. Efficient Resource Utilization:
Containers share the host OS kernel, making them more
lightweight compared to traditional virtual machines.
6. Simplified CI/CD:
Docker integrates seamlessly with CI/CD pipelines,
ensuring automated testing and deployment.

Docker Architecture
Docker's architecture consists of the following
components:

1. Docker Client:
o The interface for users to interact with Docker
(e.g., docker CLI commands).
o Sends commands to the Docker Daemon using REST
APIs.
2. Docker Daemon:
o Runs on the host machine.
o Responsible for managing Docker objects like
containers, images, and networks.
o Handles building, running, and distributing
Docker containers.
3. Docker Registry:
o A repository for storing Docker images.
o Public registries like Docker Hub or private
registries can be used.
4. Docker Objects:
o Images: Read-only templates used to create
containers.
o Containers: Instances of Docker images that can
be run, stopped, or modified.
o Volumes: Persistent storage for containers.
5. Host OS:
o The operating system on which the Docker Daemon
runs.
Five Docker Commands
1. Pull an Image:
Downloads an image from a Docker Registry.
docker pull <image-name>
Example:
docker pull nginx
2. Run a Container:
Starts a container based on an image.
docker run -d -p 8080:80 <image-name>
Example:
docker run -d -p 8080:80 nginx
3. List Running Containers:
Shows all running containers.
docker ps
4. Stop a Container:
Stops a running container.
docker stop <container-id>
5. Build an Image:
Creates a new image from a Dockerfile.
docker build -t <image-name> .
Example:
docker build -t my-app .
Explain Microservices Deployment Patterns with Diagram. 10
Ans:
2. Multiple Service instances per Host Pattern
• Description: Multiple microservices share a single
host.
• Advantages:
o Better resource utilization.
o Reduced infrastructure costs.
• Disadvantages:
o Risk of resource contention.
o Service failures may impact co-located services.

3. Service Instance per Container Pattern


• Description: Each service instance runs in its own
container.
• Advantages:
o Lightweight and portable.
o Scalability and consistency in deployments.
• Disadvantages:
o Increased complexity in container orchestration.
4. Service Instance per VM Pattern
• Description: Each service instance runs in its own
virtual machine.
• Advantages:
o Stronger isolation compared to containers.
o Customizable per-instance configurations.
• Disadvantages:
o Slower startup time compared to containers.
o Higher resource usage.

Explain in Memory Basic Authentication With the program 10


Explain the fundamental Microservices design principles 10
Mike Cohn's original test pyramid? Explain with diagram? 10
Types of Testing in Spring Spring Microservices.

Explain MSA Migration-Advantages, issues, process, and 10


its disadvantages

You might also like