---
# System prepended metadata

title: "\U0001F680 OpenShift Deployment Guide"
tags: [Openshift Deployment, Openshift]

---

# 🚀 OpenShift Deployment Guide

## Prerequisites

- OpenShift CLI (`oc`) installed
- Access to OpenShift cluster
- Docker/Podman installed (for building images)
- Git repository for your code

---

## Step 1: Prepare OpenShift Resources

### **1.1 Create Namespace/Project**
```bash
# Login to OpenShift
oc login --token=<your-token> --server=<your-server>

# Create new project
oc new-project ocp-subnet-generator

# Or use existing project
oc project ocp-subnet-generator
```

---

## Step 2: Build Strategy Options

### **Option A: S2I (Source-to-Image) - Recommended untuk Pemula**

#### **2A.1 Create BuildConfig**
```yaml
# buildconfig.yaml
apiVersion: build.openshift.io/v1
kind: BuildConfig
metadata:
  name: subnet-generator
  namespace: ocp-subnet-generator
spec:
  source:
    type: Git
    git:
      uri: https://github.com/your-username/ocp-subnet-gen.git
      ref: main
  strategy:
    type: Source
    sourceStrategy:
      from:
        kind: ImageStreamTag
        namespace: openshift
        name: nodejs:18-ubi8
  output:
    to:
      kind: ImageStreamTag
      name: subnet-generator:latest
  triggers:
    - type: ConfigChange
    - type: GitHub
      github:
        secret: your-webhook-secret
```

```bash
# Apply BuildConfig
oc apply -f buildconfig.yaml

# Start build
oc start-build subnet-generator --follow
```

---

### **Option B: Docker Build - Lebih Flexible**

#### **2B.1 Create Dockerfile** (sudah ada di project)
```dockerfile
# Dockerfile
FROM node:20-alpine AS builder

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build

FROM nginx:alpine

COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 8080

CMD ["nginx", "-g", "daemon off;"]
```

#### **2B.2 Build & Push Image**
```bash
# Login to OpenShift internal registry
oc registry login

# Build image
docker build -t subnet-generator:latest .

# Tag for OpenShift registry
docker tag subnet-generator:latest \
  image-registry.openshift-image-registry.svc:5000/ocp-subnet-generator/subnet-generator:latest

# Push to OpenShift registry
docker push image-registry.openshift-image-registry.svc:5000/ocp-subnet-generator/subnet-generator:latest
```

---

### **Option C: Binary Build - Paling Cepat untuk Development**

```bash
# Create BuildConfig for binary build
oc new-build --name=subnet-generator \
  --binary=true \
  --strategy=docker

# Build from local directory
oc start-build subnet-generator \
  --from-dir=. \
  --follow
```

---

## Step 3: Create Deployment

### **3.1 Create Deployment YAML**
```yaml
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: subnet-generator
  namespace: ocp-subnet-generator
  labels:
    app: subnet-generator
    app.kubernetes.io/name: subnet-generator
    app.kubernetes.io/component: frontend
spec:
  replicas: 2
  selector:
    matchLabels:
      app: subnet-generator
  template:
    metadata:
      labels:
        app: subnet-generator
    spec:
      containers:
      - name: subnet-generator
        image: image-registry.openshift-image-registry.svc:5000/ocp-subnet-generator/subnet-generator:latest
        ports:
        - containerPort: 8080
          protocol: TCP
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 500m
            memory: 512Mi
        livenessProbe:
          httpGet:
            path: /
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
        env:
        - name: NODE_ENV
          value: production
```

```bash
# Apply deployment
oc apply -f deployment.yaml
```

---

## Step 4: Create Service

### **4.1 Create Service YAML**
```yaml
# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: subnet-generator
  namespace: ocp-subnet-generator
  labels:
    app: subnet-generator
spec:
  selector:
    app: subnet-generator
  ports:
  - name: http
    port: 8080
    targetPort: 8080
    protocol: TCP
  type: ClusterIP
```

```bash
# Apply service
oc apply -f service.yaml
```

---

## Step 5: Create Route (Expose to Internet)

### **5.1 Create Route YAML**
```yaml
# route.yaml
apiVersion: route.openshift.io/v1
kind: Route
metadata:
  name: subnet-generator
  namespace: ocp-subnet-generator
  labels:
    app: subnet-generator
spec:
  to:
    kind: Service
    name: subnet-generator
    weight: 100
  port:
    targetPort: http
  tls:
    termination: edge
    insecureEdgeTerminationPolicy: Redirect
  wildcardPolicy: None
```

```bash
# Apply route
oc apply -f route.yaml

# Get route URL
oc get route subnet-generator -o jsonpath='{.spec.host}'
```

---

## Step 6: Complete Deployment (All-in-One)

### **6.1 Create kustomization.yaml**
```yaml
# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: ocp-subnet-generator

resources:
  - deployment.yaml
  - service.yaml
  - route.yaml

commonLabels:
  app: subnet-generator
  version: v1.0.0
```

```bash
# Deploy everything
oc apply -k .
```

---

## Step 7: CI/CD dengan OpenShift Pipelines (Tekton)

### **7.1 Install OpenShift Pipelines Operator**
```bash
# Via Web Console:
# Operators -> OperatorHub -> Search "OpenShift Pipelines" -> Install

# Or via CLI
oc apply -f https://storage.googleapis.com/tekton-releases/pipeline/latest/release.yaml
```

### **7.2 Create Pipeline**
```yaml
# pipeline.yaml
apiVersion: tekton.dev/v1beta1
kind: Pipeline
metadata:
  name: subnet-generator-pipeline
  namespace: ocp-subnet-generator
spec:
  params:
    - name: git-url
      type: string
      default: https://github.com/your-username/ocp-subnet-gen.git
    - name: git-revision
      type: string
      default: main
  workspaces:
    - name: shared-workspace
  tasks:
    - name: fetch-repository
      taskRef:
        name: git-clone
        kind: ClusterTask
      params:
        - name: url
          value: $(params.git-url)
        - name: revision
          value: $(params.git-revision)
      workspaces:
        - name: output
          workspace: shared-workspace
    
    - name: build-image
      taskRef:
        name: buildah
        kind: ClusterTask
      params:
        - name: IMAGE
          value: image-registry.openshift-image-registry.svc:5000/ocp-subnet-generator/subnet-generator:latest
      workspaces:
        - name: source
          workspace: shared-workspace
      runAfter:
        - fetch-repository
    
    - name: deploy
      taskRef:
        name: openshift-client
        kind: ClusterTask
      params:
        - name: SCRIPT
          value: |
            oc rollout restart deployment/subnet-generator -n ocp-subnet-generator
            oc rollout status deployment/subnet-generator -n ocp-subnet-generator
      runAfter:
        - build-image
```

### **7.3 Create PipelineRun**
```yaml
# pipelinerun.yaml
apiVersion: tekton.dev/v1beta1
kind: PipelineRun
metadata:
  name: subnet-generator-run-$(date +%s)
  namespace: ocp-subnet-generator
spec:
  pipelineRef:
    name: subnet-generator-pipeline
  workspaces:
    - name: shared-workspace
      volumeClaimTemplate:
        spec:
          accessModes:
            - ReadWriteOnce
          resources:
            requests:
              storage: 1Gi
```

```bash
# Run pipeline
oc create -f pipelinerun.yaml
```

---

## Step 8: Security & Best Practices

### **8.1 Create NetworkPolicy**
```yaml
# networkpolicy.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: subnet-generator-netpol
  namespace: ocp-subnet-generator
spec:
  podSelector:
    matchLabels:
      app: subnet-generator
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: openshift-ingress
    ports:
    - protocol: TCP
      port: 8080
  egress:
  - to:
    - namespaceSelector: {}
    ports:
    - protocol: TCP
      port: 443
```

### **8.2 Create ResourceQuota**
```yaml
# resourcequota.yaml
apiVersion: v1
kind: ResourceQuota
metadata:
  name: subnet-generator-quota
  namespace: ocp-subnet-generator
spec:
  hard:
    requests.cpu: "2"
    requests.memory: 4Gi
    limits.cpu: "4"
    limits.memory: 8Gi
    pods: "10"
```

### **8.3 Create LimitRange**
```yaml
# limitrange.yaml
apiVersion: v1
kind: LimitRange
metadata:
  name: subnet-generator-limits
  namespace: ocp-subnet-generator
spec:
  limits:
  - max:
      cpu: "1"
      memory: 1Gi
    min:
      cpu: 50m
      memory: 64Mi
    type: Container
```

---

## Step 9: Monitoring & Logging

### **9.1 Add Prometheus Monitoring**
```yaml
# servicemonitor.yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: subnet-generator-monitor
  namespace: ocp-subnet-generator
spec:
  selector:
    matchLabels:
      app: subnet-generator
  endpoints:
  - port: http
    interval: 30s
```

### **9.2 View Logs**
```bash
# View logs
oc logs -f deployment/subnet-generator

# View logs from all pods
oc logs -l app=subnet-generator --tail=100 -f

# View previous container logs (if crashed)
oc logs deployment/subnet-generator --previous
```

---

## Step 10: Testing & Verification

### **10.1 Check Deployment Status**
```bash
# Check all resources
oc get all -n ocp-subnet-generator

# Check deployment
oc get deployment subnet-generator -o wide

# Check pods
oc get pods -l app=subnet-generator

# Check service
oc get svc subnet-generator

# Check route
oc get route subnet-generator

# Describe pod (for troubleshooting)
oc describe pod <pod-name>
```

### **10.2 Test Application**
```bash
# Get route URL
export APP_URL=$(oc get route subnet-generator -o jsonpath='{.spec.host}')

# Test with curl
curl https://$APP_URL

# Test in browser
echo "Open: https://$APP_URL"
```

---

## Step 11: Update & Rollback

### **11.1 Update Application**
```bash
# Update image
oc set image deployment/subnet-generator \
  subnet-generator=image-registry.openshift-image-registry.svc:5000/ocp-subnet-generator/subnet-generator:v2.0.0

# Watch rollout
oc rollout status deployment/subnet-generator

# Check rollout history
oc rollout history deployment/subnet-generator
```

### **11.2 Rollback**
```bash
# Rollback to previous version
oc rollout undo deployment/subnet-generator

# Rollback to specific revision
oc rollout undo deployment/subnet-generator --to-revision=2
```

---

## Quick Commands Cheatsheet

```bash
# Login
oc login --token=xxx --server=xxx

# Create project
oc new-project ocp-subnet-generator

# Build from Git (S2I)
oc new-app nodejs:18-ubi8~https://github.com/user/repo.git --name=subnet-generator

# Build from local (Binary)
oc new-build --name=subnet-generator --binary --strategy=docker
oc start-build subnet-generator --from-dir=. --follow

# Expose service
oc expose svc/subnet-generator

# Scale
oc scale deployment subnet-generator --replicas=3

# View logs
oc logs -f deployment/subnet-generator

# Port forward (local testing)
oc port-forward svc/subnet-generator 8080:8080

# Delete everything
oc delete all -l app=subnet-generator
```

---

## Resources

- [OpenShift Documentation](https://docs.openshift.com)
- [OpenShift CLI Reference](https://docs.openshift.com/container-platform/latest/cli_reference/openshift_cli/getting-started-cli.html)
- [Tekton Pipelines](https://tekton.dev)
- [Kubernetes Best Practices](https://kubernetes.io/docs/concepts/configuration/overview/)

---

## Deployment Checklist

- [ ] Create OpenShift project
- [ ] Build container image
- [ ] Create deployment
- [ ] Create service
- [ ] Create route with TLS
- [ ] Configure resource limits
- [ ] Setup health checks
- [ ] Configure monitoring
- [ ] Test application
- [ ] Setup CI/CD pipeline
- [ ] Configure auto-scaling (optional)
- [ ] Setup backup strategy
