Powered by Blogger.

DevOps Docker Fundamentals - Part 1

No comments :

DevOps - Docker Tutorial - Part 1

Understand Docker fundamentals and Java REST API flow through diagrams and examples.

By A143MK  |  DevOps Learning Series  |  Beginner

1What Is Docker?

Docker helps you package an application and the files it needs into an image. You can use that image to start an isolated process called a container. This makes setup and delivery more repeatable across development and deployment environments.

Unlike a traditional virtual machine, a Linux container shares the host's Linux kernel instead of running a separate guest operating system. On Windows, Docker Desktop runs Linux containers using a Linux environment.

In this lesson: Explore Docker images, containers, port mapping, and Java REST API flow using diagrams.

2Key Docker Concepts

  • Dockerfile: A text file containing instructions for building an image.
  • Image: A packaged template containing your application and its runtime files.
  • Container: An instance created from an image; a running container executes its configured process.
  • Registry: A service that stores images. Docker can download public images from Docker Hub.
  • Port mapping: A connection between a port on your computer and a port in the container.
DockerfileBuild instructions
ImagePackaged template
ContainerRunning instance
Remember: Building creates an image; running creates and starts a container from that image.

3Prerequisites and Setup

  1. Install and start Docker Desktop for Windows. Follow Docker's current Windows and WSL 2 requirements.
  2. Use Linux containers, open PowerShell, and check that Docker Desktop is running.
  3. The optional Nginx command later needs internet and a free local port 8080; installation is not needed just to read this article.
docker --version
docker info

docker --version prints the CLI version. docker info should also show server information. If it cannot connect to the engine, start Docker Desktop and try again.

Safety: This is a local learning example, not a production deployment. Never put passwords or other secrets in an image or its build context.

4Docker Architecture

The Docker client sends your commands to the Docker engine. The engine manages images, containers, and networks, and downloads images from a registry when needed.

Docker CLISends commands
Docker EngineManages containers
RegistryStores images
Example: Docker Hub is a registry. Docker Desktop includes the client, engine, and other tools.

5Image Lifecycle

An image is built from Dockerfile instructions and a build context. It can be tagged, pushed to a registry, and used to create multiple containers.

BuildCreate image
RegistryShare image
RunStart container

Rebuilding an image does not change an existing container. Create a new container to use the new version. Use separate storage such as a volume for persistent data.

6Port Mapping Diagram

Port mapping connects a port on your computer to a port in the container. Below, the web server listens on port 80 inside the container.

Browserlocalhost:8080
Host port127.0.0.1:8080
NginxContainer port 80

This optional command starts a container from the public Nginx image. It needs internet to download the image; press Ctrl+C to stop it. --rm removes the container after it stops.

docker run --rm --name a143mk-nginx -p 127.0.0.1:8080:80 nginx:alpine
Binding to 127.0.0.1 limits access to your computer. If 8080 is busy, map another free host port to port 80.

7Common Docker Commands

Use these commands to inspect images and containers:

docker image ls
docker ps
docker ps -a
  • docker image ls lists local images.
  • docker ps lists running containers; docker ps -a also includes stopped containers.
  • docker logs a143mk-nginx shows logs while the example container exists.

8Docker Tools and Their Uses

These tools help you build, share, and inspect containers. Here are their key features and how they fit into later lessons.

Docker Desktop

Features: Provides a local Docker engine, CLI, and graphical dashboard for viewing images, containers, and logs.

Later use: Run and troubleshoot containers locally during development.

Docker CLI

Features: Manage Docker using commands such as docker build, docker run, and docker logs.

Later use: Automate builds and checks in terminals and CI/CD pipelines.

Docker Hub

Features: An image registry for sharing images through public or private repositories.

Later use: Publish images built in CI and pull them for deployment.

Docker Compose

Features: Define and manage multiple services, networks, and volumes together with YAML configuration.

Later use: Run a Java API and database together for local development.

Docker Buildx

Features: Offers advanced BuildKit-based builds, including multi-platform images.

Later use: Build images for different CPU architectures in CI with an appropriate builder setup.

Docker Scout

Features: Helps analyze image packages for known vulnerabilities and review remediation options.

Later use: Review image risks before delivery; scanning does not guarantee security.

Note: Availability, installation, sign-in, and plan requirements vary by tool and environment. See the official links for details.

9Java REST API Flow

Imagine a Java REST API running inside a Docker container. A client sends an HTTP request and the API returns a JSON response.

ClientGET /api/hello
DockerJava API container
Response200 OK · JSON

Java code illustration

@RestController maps a Java class to HTTP endpoints. This is an illustration of a Spring Boot controller; running it requires a Spring Boot application and its dependencies.

import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
class HelloController {
    @GetMapping("/api/hello")
    public Map<String, String> hello() {
        return Map.of("message", "Hello from Java!");
    }
}

Interactive illustration: Press the button to see an example response. This is a browser simulation; no real API request is sent.

10Troubleshooting

  • Docker command not found: Confirm Docker Desktop is installed; reopen PowerShell and check the installation instructions.
  • Cannot connect to the Docker engine: Start Docker Desktop and wait for it to be ready, then retry docker info.
  • Port 8080 is already in use: Choose another unused port, such as 127.0.0.1:8081:80, and visit http://localhost:8081.
  • Container name already exists: Inspect it with docker ps -a and choose a different name for the example.
  • Container exits or the page fails to load: While the container exists, check docker logs a143mk-nginx for errors. With --rm, it is removed when it stops.

11Quick Quiz

Choose an answer for each question and check your results.

1. What does docker build create?
2. Which command starts a container from an image?
3. Which port does the sample Nginx server use inside the container?

12What Comes Next?

You have explored Docker images, containers, port mapping, and Java API flow. Next, learn how Kubernetes manages containerized applications and how CI/CD automates building and delivering them.

Continue learning with the official Docker getting-started guide.

A143MK Blogs  |  DevOps Learning Series  |  Docker Tutorial Part 1

DevOps Docker - Part-2

No comments :

DevOps - Docker Tutorial - Part 2

Understand Docker images, Dockerfiles, volumes, and Compose with diagrams and examples.

By A143MK  |  DevOps Learning Series  |  Part 2

1Part 1 Recap

In Part 1, we learned that an image is a packaged template and a container is an instance of it. In this part, we explore how images are built and how multiple services work together.

ImageShared template
Container AFirst instance
Container BSecond instance

2Images and Layers

An image is made of layers. During a build, Docker can reuse cached results for unchanged steps, which can make repeated builds faster.

Base imageJava runtime
Applicationapp.jar
New imageReady to run
Remember: Image layers are generally read-only; a container gets its own writable layer.

Interactive example: See the build stages. This is a browser simulation; it does not run Docker.

3Understanding a Dockerfile

This illustrative Dockerfile packages a Java REST API. It assumes an executable Java 17-compatible JAR already exists in the build context at target/app.jar. It is a code illustration, not a complete Java project.

FROM eclipse-temurin:17-jre
WORKDIR /app
COPY target/app.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
  • FROM selects a base runtime image and WORKDIR sets the working directory.
  • COPY places the JAR from the build context into the image.
  • EXPOSE documents the intended container port; it does not publish it. ENTRYPOINT starts the Java application.
Safety: Do not put passwords in images or build contexts. For real deployments, use trusted base images, controlled versions, and appropriate secret management.

4Image Tags and Registry

A tag identifies an image name and version, such as my-api:1.0. A registry stores images for sharing. Tags can be moved; an image digest provides a more precise identifier.

Build imagemy-api:1.0
RegistryShare image
DeploymentPull image

docker image ls lists local images. Before pushing, check the target repository and required permissions.

5Container Data and Volumes

Data in a container's writable layer is lost when that container is removed. A Docker volume can keep data separate from the container's lifecycle.

Database containerReads and writes data
Docker volumeData outside container
A volume is not automatically a backup. Removing a volume can delete its data; plan backups and recovery for production.

6Docker Compose

Compose uses YAML to define multiple services as one application. The configuration below illustrates two separate services; Nginx does not automatically use Redis.

services:
  web:
    image: nginx:alpine
    ports:
      - "127.0.0.1:8080:80"
  cache:
    image: redis:7-alpine
ComposeManages services
webNginx :80
cacheRedis :6379

With a Compose configuration, docker compose up starts services and docker compose down stops them and removes their containers and networks. Use volume-removal options carefully.

Properly configured containers can reach one another by service name on the default Compose network, such as cache:6379.

7Java REST API Flow

A typical Java API receives a request, reads data from a database, and returns JSON. Containerization does not automatically make the application secure or scalable.

ClientGET /api/items
Java APIREST API in container
DatabaseData storage

The actual API port, database connection, authentication, and health checks depend on the application's configuration. This diagram illustrates the concept only.

8Better and Safer Builds

The build context contains the files available to the builder. Including only what is needed can speed up builds and reduce accidental exposure of unnecessary data.

Build context and .dockerignore

These are example .dockerignore patterns. Check them against your project: the Dockerfile above needs target/app.jar, so do not exclude the entire target directory.

.git
.env
*.log
Secret safety: Do not rely on these patterns alone. Keep secrets out of the build context and image; use BuildKit secret mounts for secrets needed during a build.

Cache and multi-stage builds

When a step's inputs change, it and dependent later steps may need to run again. Placing less frequently changed steps before frequently changed application code can improve cache reuse.

Build stageCompile and test code
ArtifactCopy required JAR
Runtime stageRuntime requirements only

A multi-stage Dockerfile can separate build and runtime stages. Copying only the required artifact into the final image can make it smaller without including build tools.

Read more: build context, multi-stage builds, and build secrets.

9Configuration and Networking

Application settings may differ between development, test, and production. Pass non-sensitive settings at runtime; use your environment's secret manager for passwords and API keys.

  • Environment variables: Useful for settings such as ports and profiles, but they may be visible through inspection or logs. Use appropriate secret management for sensitive data.
  • Service address: On a default Compose network, a Java API can reach a database by service name, such as db:5432. Inside a container, localhost refers to that container.
  • Health and readiness: A running process does not guarantee a ready service. Configure appropriate application health checks and handle a database that starts late or becomes temporarily unavailable.
  • Least privilege: Use a non-root user and minimum required permissions where possible. First check which writable paths and ports the application needs.
Java APIClient inside container
db:5432Compose service name
DatabasePrivate network

The example db address works only when that Compose project has a database service named db. The Nginx/Redis example above does not define one.

10Inspecting and Troubleshooting

In these commands, a143mk-docker2-nginx is an example container name. Run them only against your own container; choose another name if it is already in use.

For an optional local test, start Docker, make sure internet is available and port 8080 is free. This starts a background container from the public Nginx image:

docker run -d --name a143mk-docker2-nginx -p 127.0.0.1:8080:80 nginx:alpine

While it is running, open http://localhost:8080; you should see the Nginx welcome page. In another terminal, inspect status, logs, and port mapping. The container must be running to view resource usage.

docker ps -a
docker logs --tail 50 a143mk-docker2-nginx
docker inspect --format '{{.State.ExitCode}}' a143mk-docker2-nginx
docker port a143mk-docker2-nginx
docker stats --no-stream a143mk-docker2-nginx
  • Exited container: Read its logs and check its exit status. For example, invalid configuration or a failed main process can stop a container.
  • Page does not load: Check that the container is running, the application listens on the right container port, and the host port is mapped. If 8080 is busy, choose another free host port.
  • Database connection fails: Check the service name, network, credentials, and database readiness. Do not publish secrets in logs or screenshots.

If you started the container above and no longer need it, stop and remove only that container:

docker stop a143mk-docker2-nginx
docker rm a143mk-docker2-nginx
For Compose: In a configured project, docker compose ps shows status and docker compose logs shows service logs.

11Developer Checklist

Before sharing an image with your team or CI/CD pipeline, consider these points:

  • Run tests during the build workflow and review the results; a successful image build alone does not mean application tests passed.
  • Choose trusted base images, control versions, and regularly review dependencies and known vulnerabilities.
  • Use appropriate configuration, secret management, least privilege, and only the required network ports.
  • Define logging, health checks, resource limits, persistent data, and backup needs for your application.
  • Identify images by tag and, where possible, digest so the same tested image can be deployed.

12Quick Quiz

Choose an answer for each question and check your results.

1. What does EXPOSE do?
2. What can help retain data after a container is removed?
3. What is Compose mainly used for?

13What Comes Next?

You have explored image layers, Dockerfiles, volumes, and Compose. Next, learn Kubernetes fundamentals and how containers are deployed.

Learn more: Dockerfile documentation and Docker Compose documentation.

A143MK Blogs  |  DevOps Learning Series  |  Docker Tutorial Part 2

DevOps - Kubernetes Part-3

No comments :

DevOps - Kubernetes Tutorial - Part 3

Learn Kubernetes with architecture, developer tools, and a real Java API example.

By A143MK  |  DevOps Learning Series  |  Part 3

1From Docker to Kubernetes

In Docker Parts 1 and 2, we explored container images, volumes, and Compose. Kubernetes helps maintain the desired state of container workloads across machines. Docker can build images; Kubernetes manages running them in a cluster.

Application codeJava API
Container imageBuild and registry
KubernetesDeploy and manage
Kubernetes does not automatically make an application secure or guarantee zero downtime. Design, capacity, and testing still matter.

2Cluster Architecture

The control plane manages desired state, while worker nodes run application Pods. This simplified diagram is conceptual; actual cluster layouts vary.

kubectlSend requests
API serverCluster API
Control planeetcd, scheduler, controllers
Worker nodeskubelet, runtime, Pods
  • API server and etcd: The API accepts requests; etcd stores cluster state.
  • Scheduler and controllers: The scheduler assigns Pods to suitable nodes; controllers reconcile actual state toward desired state.
  • Node and kubelet: A node runs applications; kubelet manages Pods and the container runtime on that node.

3Essential Concepts

  • Pod: The smallest deployable unit, containing one or more cooperating containers.
  • Deployment: Manages desired Pod replicas and updates. It attempts to replace failed Pods.
  • Service: Provides a stable network identity for selected Pods. ClusterIP is available inside the cluster by default.
  • Namespace and labels: A namespace organizes resources; labels and selectors connect resources.
  • ConfigMap and Secret: ConfigMaps hold non-sensitive configuration. Configure appropriate access control and encryption for Secrets; base64 alone is not protection.

4Developer Tools

  • kubectl: Command-line tool for inspecting clusters, applying resources, logs, and debugging.
  • Minikube or kind: Local clusters for learning and testing. kind needs a container runtime such as Docker; Minikube prerequisites depend on its driver.
  • Helm: Packages and configures related Kubernetes resources as charts. Review chart contents and sources before installing.
  • k9s: Terminal UI for inspecting resources and logs. It also uses your Kubernetes context and permissions.
  • Metrics Server: When configured, supplies metrics for kubectl top and resource-based autoscaling; it is not a complete monitoring solution.

Official documentation: kubectl, Minikube, kind, Helm, k9s.

5Live Example Prerequisites

The following example runs a real Java HTTP API in two Kubernetes Pods. Use a personal local test cluster only; it has no database or authentication.

  1. kubectl and a running local Kubernetes cluster are required. The node needs internet to pull the public eclipse-temurin:17-jdk image.
  2. Allow enough CPU and memory for two Pods; pulling the image and starting Java can take time. Host port 8080 must be free.
  3. Run the checks below first. Continue only on your own local cluster and stop if the namespace or example names already exist.
kubectl config current-context
kubectl get nodes
kubectl get namespace a143mk-k8s-demo

A not-found response to the last command means the namespace can be created. Do not continue on another error, the wrong context, or an existing namespace.

Important: These commands modify the selected Kubernetes context. Do not run this example on a production or shared cluster.

6Java API and Kubernetes YAML

Below is the complete example: Java source in a ConfigMap, a Deployment that runs it, and a Service that reaches the Pods. Save the single YAML as a143mk-k8s-demo.yaml. No separate project or Docker build is required.

Browserlocalhost:8080
kubectlport-forward
Serviceport 80 → 8080
Java PodsGET /api/hello

Within the cluster, the Service routes traffic to ready Pods matching its selector. In this local port-forward example, kubectl selects one Pod; it does not demonstrate load balancing.

apiVersion: v1
kind: ConfigMap
metadata:
  name: a143mk-api-source
data:
  HelloApi.java: |
    import com.sun.net.httpserver.HttpServer;
    import java.net.InetSocketAddress;
    import java.nio.charset.StandardCharsets;

    public class HelloApi {
      public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/", exchange -> {
          try (exchange) {
            String path = exchange.getRequestURI().getPath();
            int status;
            String body;
            if (!"GET".equals(exchange.getRequestMethod())) {
              exchange.getResponseHeaders().set("Allow", "GET");
              status = 405;
              body = "{\"error\":\"Method not allowed\"}";
            } else if ("/api/hello".equals(path)) {
              status = 200;
              body = "{\"message\":\"Hello from Kubernetes!\"}";
            } else if ("/health".equals(path)) {
              status = 200;
              body = "{\"status\":\"UP\"}";
            } else {
              status = 404;
              body = "{\"error\":\"Not found\"}";
            }
            byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
            exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
            exchange.getResponseHeaders().set("Access-Control-Allow-Origin", "*");
            exchange.getResponseHeaders().set("Cache-Control", "no-store");
            exchange.sendResponseHeaders(status, bytes.length);
            exchange.getResponseBody().write(bytes);
          }
        });
        server.start();
        System.out.println("Java API listening on port 8080");
      }
    }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: a143mk-api
spec:
  replicas: 2
  selector:
    matchLabels:
      app: a143mk-api
  template:
    metadata:
      labels:
        app: a143mk-api
    spec:
      containers:
        - name: api
          image: eclipse-temurin:17-jdk
          command: ["java", "--add-modules", "jdk.httpserver", "/app/HelloApi.java"]
          ports:
            - containerPort: 8080
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              memory: 512Mi
          startupProbe:
            httpGet:
              path: /health
              port: 8080
            periodSeconds: 10
            failureThreshold: 30
          readinessProbe:
            httpGet:
              path: /health
              port: 8080
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /health
              port: 8080
            periodSeconds: 10
          volumeMounts:
            - name: source
              mountPath: /app
              readOnly: true
      volumes:
        - name: source
          configMap:
            name: a143mk-api-source
---
apiVersion: v1
kind: Service
metadata:
  name: a143mk-api
spec:
  selector:
    app: a143mk-api
  ports:
    - port: 80
      targetPort: 8080
  type: ClusterIP
This is for learning only: source is in a ConfigMap, the JDK runs it at startup, and CORS allows all origins. For production, build an application image, restrict CORS, and add authentication, security, and real dependency health checks.

The startup probe allows time for slow startup; a failed readiness probe makes the Pod unavailable for normal Service traffic. Repeated liveness failures can cause a container restart.

7Deploy and Test the API

After completing the prerequisite checks, open a terminal where you saved the YAML. Create the namespace, apply the resources, and wait for rollout:

kubectl create namespace a143mk-k8s-demo
kubectl -n a143mk-k8s-demo apply -f a143mk-k8s-demo.yaml
kubectl -n a143mk-k8s-demo rollout status deployment/a143mk-api --timeout=300s
kubectl -n a143mk-k8s-demo get deployment,pods,service

If rollout does not succeed, stop and see troubleshooting below. Once it succeeds, start port forwarding in this terminal and leave it running:

kubectl -n a143mk-k8s-demo port-forward service/a143mk-api 8080:80

In another terminal, call the real API from PowerShell or open http://localhost:8080/api/hello in a browser:

Invoke-RestMethod http://localhost:8080/api/hello
Invoke-RestMethod http://localhost:8080/health

Successful JSON responses are {"message":"Hello from Kubernetes!"} and {"status":"UP"}. Press Ctrl+C in the port-forward terminal to stop it.

8Live Browser Request

This button sends a real GET http://localhost:8080/api/hello request; it is not a simulation. Run the example above and keep port forwarding active first.

The button calls localhost on the computer running the browser. Browser or blog security policies may block local requests; if so, use the PowerShell command above.

9Scaling and Troubleshooting

Inspect status, details, and logs in the demo namespace. Run the scale command only on the demo Deployment:

kubectl -n a143mk-k8s-demo get pods -l app=a143mk-api
kubectl -n a143mk-k8s-demo describe deployment a143mk-api
kubectl -n a143mk-k8s-demo logs deployment/a143mk-api --tail=50
kubectl -n a143mk-k8s-demo scale deployment/a143mk-api --replicas=3
kubectl -n a143mk-k8s-demo rollout status deployment/a143mk-api --timeout=300s

Scaling needs enough node resources. Reapplying the YAML may restore its desired replicas: 2. The Deployment logs command shows one Pod's logs, not all Pods.

  • Pending: Inspect events with kubectl -n a143mk-k8s-demo describe pod POD_NAME; check node resources and scheduling. Replace POD_NAME with your Pod name.
  • ImagePullBackOff: Check the image name, network, and registry access in Pod events.
  • CrashLoopBackOff or not ready: Inspect Pod events, container logs, memory, and probe paths. For previous container logs use kubectl -n a143mk-k8s-demo logs POD_NAME --previous.
  • API unreachable: Check rollout, ready Pods, the Service selector, ports, and the running port-forward terminal.

Remove only your demo resources

If you created these three resources and no longer need them, stop port forwarding first, then delete them. The namespace is retained; do not delete other resources.

kubectl -n a143mk-k8s-demo delete deployment/a143mk-api service/a143mk-api configmap/a143mk-api-source

10Production Readiness

  • Build and scan a tested application image, use a pinned image digest, and include tests and review in CI.
  • Configure least-privilege RBAC, appropriate Secret protection, non-root containers, and network policies for your cluster.
  • Design readiness and liveness for the application's behavior. A process-only check does not prove a database is available.
  • Choose CPU and memory requests/limits from measurements; plan capacity, logs, metrics, alerts, and rollback.
  • For persistent data, choose appropriate storage and test backup and recovery. Ingress or Gateway, TLS, and external access require separate configuration.

11Quick Quiz

1. What manages desired Pod replicas?
2. How does a Service select Pods?
3. What happens when a readiness probe fails?

12What to Learn Next

Next, explore rolling updates, ConfigMaps and Secrets, persistent storage, Ingress, and building and deploying images through CI/CD pipelines.

Official documentation: Kubernetes concepts and Kubernetes tutorials.

A143MK Blogs  |  DevOps Learning Series  |  Kubernetes Tutorial Part 3