Skip to content

Linux_Practical_Interview_751 1000

Linux Practical Interview Questions (751-1000)

Section titled “Linux Practical Interview Questions (751-1000)”

Q751: How do you configure system performance monitoring?

Section titled “Q751: How do you configure system performance monitoring?”

Answer:

/etc/default/sysstat
# Use SAR for historical data
ENABLED="true"
# Enable collection
systemctl enable sysstat
systemctl start sysstat
# View reports
sar -u 1 5 # CPU usage
sar -r 1 5 # Memory
sar -b 1 5 # I/O
sar -n DEV 1 5 # Network

Q752: How do you configure custom metrics collection?

Section titled “Q752: How do you configure custom metrics collection?”

Answer:

Terminal window
# Use node_exporter
docker run -d -p 9100:9100 prom/node-exporter
# Custom metrics
#!/bin/bash
while true; do
echo "custom_metric $(date +%s)" | nc -q1 localhost 9090
sleep 10
done

Q753: How do you set up centralized logging?

Section titled “Q753: How do you set up centralized logging?”

Answer:

Terminal window
# Using rsyslog
# Server
$ModLoad imtcp
$InputTCPServerRun 514
# Client
*.* @@logging-server:514
# Or ELK stack
# Filebeat -> Logstash -> Elasticsearch -> Kibana

Q754: How do you configure log retention policies?

Section titled “Q754: How do you configure log retention policies?”

Answer:

/etc/logrotate.d/myapp
# logrotate
/var/log/myapp/*.log {
daily
rotate 90
compress
delaycompress
missingok
create 0640 user group
}
# Or with systemd
# journald.conf
SystemMaxUse=500M
MaxFileSec=1month

Answer:

Terminal window
# Configure auditd
auditctl -w /etc/passwd -p wa -k identity
auditctl -w /etc/shadow -p wa -k identity
auditctl -w /var/log/ -p wa -k logfiles
# Search
ausearch -k identity
aureport -f

Q756: How do you set up file integrity monitoring?

Section titled “Q756: How do you set up file integrity monitoring?”

Answer:

Terminal window
# Install AIDE
aideinit
# Configure
# /etc/aide/aide.conf
/etc/shadow NORMAL
/etc/passwd NORMAL
/var/log NORMAL
# Daily check
0 5 * * * /usr/bin/aide --check

Q757: How do you implement intrusion detection?

Section titled “Q757: How do you implement intrusion detection?”

Answer:

Terminal window
# OSSEC
# Install
apt install ossec-hids-agent
# Configure
# /var/ossec/etc/ossec.conf
<active-response>
<disabled>no</disabled>
</active-response>
# Rules in
# /var/ossec/etc/rules/local_rules.xml

Q758: How do you configure network monitoring?

Section titled “Q758: How do you configure network monitoring?”

Answer:

Terminal window
# Use Prometheus + blackbox exporter
docker run -d -p 9115:9110 prom/blackbox-exporter
# Configure
# /etc/blackbox/blackbox.yml
modules:
http_2xx:
prober: http
# Prometheus scrape
- job_name: blackbox
metrics_path: /probe
static_configs:
- targets:
- https://example.com

Q759: How do you set up service monitoring?

Section titled “Q759: How do you set up service monitoring?”

Answer:

Terminal window
# Use Prometheus
- job_name: 'service'
static_configs:
- targets: ['localhost:8080']
# Health check endpoint
#!/bin/bash
curl -f http://localhost:8080/health || exit 1

Q760: How do you implement application performance monitoring?

Section titled “Q760: How do you implement application performance monitoring?”

Answer:

Terminal window
# Use APM (Application Performance Monitoring)
# Options: New Relic, Datadog, Dynatrace, Elastic APM
# Example: Elastic APM
# Install agent
pip install elastic-apm
# Configure
# apm.py
from elasticapm import Client
client = Client(service_name='myapp')

Q761: How do you configure system hardening scripts?

Section titled “Q761: How do you configure system hardening scripts?”

Answer:

Terminal window
# CIS Benchmarks
# Use Lynis
lynis audit system
# Use OpenSCAP
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis \
--results scan-results.xml /usr/share/xml/scap/ssg/content/ssg-ubuntu2004-ds.xml
# Use CIS-CAT Pro

Q762: How do you implement automated patching?

Section titled “Q762: How do you implement automated patching?”

Answer:

Terminal window
# unattended-upgrades
apt install unattended-upgrades
# Configure
# /etc/apt/apt.conf.d/50unattended-upgrades
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
};
# Enable
dpkg-reconfigure -plow unattended-upgrades

Q763: How do you configure vulnerability scanning?

Section titled “Q763: How do you configure vulnerability scanning?”

Answer:

Terminal window
# Use OpenVAS
# Install
apt install openvas
# Setup
greenbone-nvt-sync
openvasmd --rebuild
# Run scan
openvas -o scan-report.xml --target=target-id
# Or use Trivy
trivy image nginx:latest
trivy fs .

Q764: How do you implement change management?

Section titled “Q764: How do you implement change management?”

Answer:

Terminal window
# Use configuration management
# Ansible, Puppet, Chef, Salt
# Track changes
# GitOps with ArgoCD/Flux
# Example: Ansible Tower
# Create job templates
# Track execution history
# Require approval for production

Q765: How do you configure compliance reporting?

Section titled “Q765: How do you configure compliance reporting?”

Answer:

Terminal window
# Use OpenSCAP
oscap xccdf generate report scan-results.xml > report.html
# Use Lynis
lynis audit system --report-file /root/lynis-report.log
# Use AIDE
aide --check --report /root/aide-report.log

Q766: How do you implement data classification?

Section titled “Q766: How do you implement data classification?”

Answer:

Terminal window
# Define classification levels
# Public, Internal, Confidential, Restricted
# Implement with SELinux
semanage fcontext -a -t confidential_t "/srv/confidential(/.*)?"
# Use ACLs
setfacl -R -m u:admin:rwX /data/confidential
setfacl -R -m g:auditors:rX /data/confidential

Q767: How do you configure data loss prevention?

Section titled “Q767: How do you configure data loss prevention?”

Answer:

Terminal window
# Use OpenDLP
# Or use content filters
# iptables example
iptables -A OUTPUT -m string --string "confidential" -j DROP
# Or use auditd
auditctl -w /data/ -p wa -k data_loss

Q768: How do you implement encryption at rest?

Section titled “Q768: How do you implement encryption at rest?”

Answer:

Terminal window
# LUKS
cryptsetup luksFormat /dev/sdb1
cryptsetup open /dev/sdb1 crypt_vol
mkfs.ext4 /dev/mapper/crypt_vol
# File-level encryption
# Use GPG or age
gpg -c file.txt
# Database encryption
# PostgreSQL: pgcrypto extension

Q769: How do you implement encryption in transit?

Section titled “Q769: How do you implement encryption in transit?”

Answer:

Terminal window
# TLS/SSL everywhere
# Nginx
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# Database
# PostgreSQL: ssl = on
# MySQL: require ssl
# SSH
# Use strong ciphers
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com

Q770: How do you configure key management?

Section titled “Q770: How do you configure key management?”

Answer:

Terminal window
# HashiCorp Vault
vault server -dev
# Store secrets
vault kv put secret/myapp api_key=xxx
# Use in application
# Use kubernetes-secrets-injector or external-secrets-operator

Q771: How do you implement access control?

Section titled “Q771: How do you implement access control?”

Answer:

Terminal window
# RBAC (Role-Based Access Control)
# Linux: groups and sudo
# SELinux
# Enable and configure contexts
semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
# AppArmor
# Create profiles for applications

Q772: How do you configure network segmentation?

Section titled “Q772: How do you configure network segmentation?”

Answer:

Terminal window
# VLANs
vconfig add eth0 100
vconfig add eth0 200
# Firewalls
# DMZ, internal, database tiers
# Kubernetes
# NetworkPolicies
kubectl apply -f network-policy.yaml

Q773: How do you implement zero trust network?

Section titled “Q773: How do you implement zero trust network?”

Answer:

Terminal window
# mTLS for all communication
# Use service mesh (Istio, Linkerd)
# Certificate-based authentication
# Short-lived certificates
# Continuous verification
# Real-time policy enforcement

Answer:

Terminal window
# Rate limiting
# Nginx
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
# Authentication
# JWT tokens
# OAuth2/OIDC
# API Gateway
# Kong, AWS API Gateway, Tyk

Q775: How do you implement DDoS protection?

Section titled “Q775: How do you implement DDoS protection?”

Answer:

Terminal window
# Rate limiting
# Nginx
limit_req_zone $binary_remote_addr zone=ddos:10m rate=100r/s;
# Fail2ban
# Block repeated offenders
# Cloud protection
# AWS Shield, Cloudflare, Akamai

Q776: How do you configure backup verification?

Section titled “Q776: How do you configure backup verification?”

Answer:

# Automated restore test
#!/bin/bash
# Restore to test environment
# Verify data integrity
# Report results
# Add to cron
# 0 2 * * 0 /opt/backup-verify.sh

Q777: How do you implement disaster recovery testing?

Section titled “Q777: How do you implement disaster recovery testing?”

Answer:

Terminal window
# Test procedures
# 1. Document RTO/RPO
# 2. Create runbooks
# 3. Test failover
# 4. Verify data
# 5. Document lessons
# Schedule quarterly tests

Q778: How do you configure high availability?

Section titled “Q778: How do you configure high availability?”

Answer:

Terminal window
# Load balancer
# HAProxy, NGINX
# Clustering
# Pacemaker + Corosync
# Keepalived for VIP
# Database
# Master-slave or multi-master
# Connection pooling

Q779: How do you implement load balancing?

Section titled “Q779: How do you implement load balancing?”

Answer:

/etc/haproxy/haproxy.cfg
# HAProxy configuration
backend servers
balance roundrobin
server s1 192.168.1.10:80 check
server s2 192.168.1.11:80 check
# Health checks
# Check inter 3s fall 2 rise 1

Answer:

Terminal window
# Kubernetes HPA
kubectl autoscale deployment myapp --cpu-percent=70 --min=2 --max=10
# Cloud provider
# AWS Auto Scaling Groups
# GCP Managed Instance Groups
# Azure Virtual Machine Scale Sets

Answer:

Terminal window
# Jenkins
# Install
apt install jenkins
# Create pipeline
# Jenkinsfile
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'make build'
}
}
stage('Test') {
steps {
sh 'make test'
}
}
stage('Deploy') {
steps {
sh 'make deploy'
}
}
}
}

Answer:

.gitlab-ci.yml
stages:
- build
- test
- deploy
build:
stage: build
script:
- docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
- docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
deploy:
stage: deploy
script:
- kubectl apply -f deployment.yaml
only:
- main

Answer:

.github/workflows/ci.yml
name: CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run tests
run: make test
- name: Build
run: make build

Q784: How do you configure container registries?

Section titled “Q784: How do you configure container registries?”

Answer:

Terminal window
# Harbor
# Install
docker run -d -p 80:80 -p 443:443 -v /data/harbor:/etc/harbor --name harborVMWare/harbor
# Push
docker push myregistry.com/myimage:tag
# Pull with credentials
docker login myregistry.com

Q785: How do you implement infrastructure as code?

Section titled “Q785: How do you implement infrastructure as code?”

Answer:

Terminal window
# Terraform example
# main.tf
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web" {
ami = "ami-xxx"
instance_type = "t3.micro"
tags = {
Name = "web"
}
}
# Commands
terraform init
terraform plan
terraform apply

Q786: How do you use Ansible for configuration management?

Section titled “Q786: How do you use Ansible for configuration management?”

Answer:

playbook.yml
- hosts: webservers
become: yes
tasks:
- name: Install nginx
apt:
name: nginx
state: present
- name: Start nginx
service:
name: nginx
state: started
enabled: yes

Answer:

recipe.rb
package 'nginx' do
action :install
end
service 'nginx' do
action [:enable, :start]
end
template '/etc/nginx/nginx.conf' do
source 'nginx.conf.erb'
mode '0644'
notifies :restart, 'service[nginx]'
end

Q788: How do you use Puppet for automation?

Section titled “Q788: How do you use Puppet for automation?”

Answer:

init.pp
class nginx {
package { 'nginx':
ensure => installed,
}
service { 'nginx':
ensure => running,
enable => true,
}
}
include nginx

Q789: How do you use Vagrant for development?

Section titled “Q789: How do you use Vagrant for development?”

Answer:

# Vagrantfile
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/focal64"
config.vm.network "private_network", ip: "192.168.33.10"
config.vm.synced_folder "./data", "/vagrant_data"
config.vm.provision "shell", inline: <<-SHELL
apt-get update
apt-get install -y nginx
SHELL
end

Answer:

{
"builders": [
{
"type": "amazon-ebs",
"region": "us-east-1",
"source_ami": "ami-xxx",
"instance_type": "t2.micro",
"ami_name": "my-custom-image"
}
],
"provisioners": [
{
"type": "shell",
"inline": [
"apt-get update",
"apt-get install -y nginx"
]
}
]
}

Q791: How do you troubleshoot kernel panics?

Section titled “Q791: How do you troubleshoot kernel panics?”

Answer:

Terminal window
# Check logs
journalctl -b -1
dmesg
# Enable crash dump
# /etc/default/kdump-tools
USE_KDUMP=1
# After crash
# Analyze with crash utility
crash /var/crash/vmcore /usr/lib/debug/boot/vmlinux-$(uname -r)

Answer:

Terminal window
# Check OOM killer
dmesg | grep -i "out of memory"
journalctl -k | grep -i "killed process"
# Check process
ps aux --sort=-%mem | head
# Tune kernel
# /etc/sysctl.conf
vm.overcommit_memory = 1
vm.swappiness = 10

Q793: How do you troubleshoot disk I/O bottlenecks?

Section titled “Q793: How do you troubleshoot disk I/O bottlenecks?”

Answer:

Terminal window
# Check I/O
iostat -x 1
# Check processes
iotop
# Check latency
iostat -x 1 | grep await
# Check queue
cat /proc/diskstats

Q794: How do you troubleshoot network latency?

Section titled “Q794: How do you troubleshoot network latency?”

Answer:

Terminal window
# Check latency
ping -c 10 host
mtr host
# Check routes
ip route
traceroute host
# Check DNS
dig host
nslookup host
# Check firewall
iptables -L -n

Q795: How do you troubleshoot high CPU usage?

Section titled “Q795: How do you troubleshoot high CPU usage?”

Answer:

Terminal window
# Top processes
top
htop
# Per-process
ps aux --sort=-%cpu | head
# Threads
ps -eLf -p PID
# System-wide
mpstat -P ALL 1

Q796: How do you troubleshoot memory leaks?

Section titled “Q796: How do you troubleshoot memory leaks?”

Answer:

Terminal window
# Check memory
free -h
# Monitor process
pmap -x PID
# Use valgrind
valgrind --leak-check=full ./program
# Use systemd-cgtop
systemd-cgtop

Q797: How do you troubleshoot service crashes?

Section titled “Q797: How do you troubleshoot service crashes?”

Answer:

Terminal window
# Check status
systemctl status service
# Check logs
journalctl -u service -n 50
journalctl -xe
# Core dumps
# Enable
# /etc/security/limits.conf
* soft core unlimited
# Analyze
coredumpctl
coredumpctl gdb PID

Answer:

Terminal window
# Verbose SSH
ssh -vvv user@host
# Check logs
tail -f /var/log/auth.log
# Test connectivity
nc -zv host 22
# Check keys
ls -la ~/.ssh/

Q799: How do you troubleshoot DNS resolution?

Section titled “Q799: How do you troubleshoot DNS resolution?”

Answer:

Terminal window
# Test DNS
nslookup host
dig host +trace
# Check resolv.conf
cat /etc/resolv.conf
# Flush DNS
systemd-resolve --flush-caches
# Test specific server
nslookup host 8.8.8.8

Q800: How do you troubleshoot database performance?

Section titled “Q800: How do you troubleshoot database performance?”

Answer:

Terminal window
# PostgreSQL
EXPLAIN ANALYZE SELECT * FROM table;
# MySQL
EXPLAIN FORMAT=JSON SELECT * FROM table;
# Check connections
SELECT * FROM pg_stat_activity;
# Check slow queries
SHOW VARIABLES LIKE 'slow_query_log';

Q801: How do you configure kernel live patching?

Section titled “Q801: How do you configure kernel live patching?”

Answer:

Terminal window
# Ubuntu Livepatch
# Install
snap install canonical-livepatch
# Enable
sudo canonical-livepatch enable
# Check status
canonical-livepatch status

Answer:

Terminal window
# Install
apt install kpatch-dkms
# Create patch
kpatch-build patch.diff
# Apply
kpatch load patch.ko
# List
kpatch list

Q803: How do you configure dynamic tracing?

Section titled “Q803: How do you configure dynamic tracing?”

Answer:

Terminal window
# Use bpftrace
apt install bpftrace
# Write script
# mytrace.bt
#!/usr/bin/bpftrace
BEGIN
{
printf("Tracing... Hit Ctrl-C to end.\n")
}
kprobe:do_nice
{
printf("PID %d nice: %d\n", pid, arg1)
}
# Run
bpftrace mytrace.bt

Answer:

Terminal window
# Enable
mount -t debugfs nodev /sys/kernel/debug
# List available tracers
cat /sys/kernel/debug/tracing/available_tracers
# Set tracer
echo function > /sys/kernel/debug/tracing/current_tracer
# Enable function
echo '*tcp*' > /sys/kernel/debug/tracing/set_ftrace_filter
# Read
cat /sys/kernel/debug/tracing/trace

Answer:

Terminal window
# Install
apt install perfetto
# Create config
# config.pbtxt
buffers: {
size_kb: 63488
fill_policy: DISCARD
}
data_sources: {
config {
name: "linux.ftrace"
ftrace_config {
ftrace_events: "sched/sched_switch"
ftrace_events: "power/cpu_frequency"
}
}
}
# Trace
perfetto -c config.pbtxt -o trace.perfetto

Answer:

xdp_drop.c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
SEC("xdp_drop")
int xdp_drop_prog(struct xdp_md *ctx) {
return XDP_DROP;
}
char _license[] SEC("license") = "GPL";

Answer:

Terminal window
# Install
apt install criu
# Checkpoint
criu dump -t PID --images-dir /tmp/checkpoint
# Restore
criu restore --images-dir /tmp/checkpoint
# Pre-dump
criu predump -t PID --images-dir /tmp/checkpoint

Q808: How do you use crictl with Kata Containers?

Section titled “Q808: How do you use crictl with Kata Containers?”

Answer:

Terminal window
# Install Kata Containers
kata-runtime --version
# Configure containerd
# /etc/containerd/config.toml
[plugins]
[plugins."io.containerd.grpc.v1.cri"]
runtime_handler = "io.containerd.kata.v2"
# Use runtime
crictl run --runtime io.containerd.kata.v2 container.json pod.json

Answer:

Terminal window
# Install
apt install runsc
# Configure containerd
# /etc/containerd/config.toml
[plugins]
[plugins."io.containerd.grpc.v1.cri"]
runtime_handler = "runsc"
# Run
crictl run --runtime runsc container.json pod.json

Answer:

Terminal window
# Install
apt install firecracker
# Create microVM
# config.json
{
"boot-source": "vmlinux",
"kernel-image": "vmlinux",
"drive": {
"path": "rootfs.ext4"
},
"network-interfaces": [
{
"guest-device": "eth0"
}
]
}
# Run
firecracker --config-file config.json

Answer:

Terminal window
# Install with high availability
# Use embedded etcd or external DB
# Install
curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="--write-kubeconfig-mode 644" sh -
# Token
cat /var/lib/rancher/k3s/server/node-token
# Add agent
curl -sfL https://get.k3s.io | K3S_URL=https://server:6443 K3S_TOKEN=TOKEN sh -

Answer:

Terminal window
# Use Longhorn
# Install
kubectl apply -f https://raw.githubusercontent.com/longhorn/longhorn/master/deploy/longhorn.yaml
# Create PVC
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mypvc
spec:
accessModes:
- ReadWriteOnce
storageClassName: longhorn
resources:
requests:
storage: 1Gi

Q813: How do you configure K3s service mesh?

Section titled “Q813: How do you configure K3s service mesh?”

Answer:

Terminal window
# Install Linkerd
curl -sL https://run.linkerd.io/install | sh
# Inject
kubectl get deploy -o yaml | linkerd inject - | kubectl apply -f -
# Check
linkerd viz dashboard

Answer:

Terminal window
# Install
curl -sSLf https://get.k0sproject.io | sh
# Start
k0s controller
# Add worker
k0s worker --token-file /var/lib/k0s/worker.token

Answer:

Terminal window
# Install
snap install microk8s --classic
# Enable addons
microk8s enable dns storage ingress
# Check status
microk8s status
# Use kubectl
microk8s kubectl get pods

Q816: How do you use Minikube with drivers?

Section titled “Q816: How do you use Minikube with drivers?”

Answer:

Terminal window
# Install
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
install minikube-linux-amd64 /usr/local/bin/minikube
# Start with Docker
minikube start --driver=docker
# Start with KVM
minikube start --driver=kvm2
# Addons
minikube addons enable ingress

Answer:

Terminal window
# Install
go install sigs.k8s.io/kind@v0.20.0
# Create cluster
kind create cluster
# Custom cluster
kind create cluster --config kind-config.yaml
# Load image
kind load docker-image myimage:latest

Answer:

Terminal window
# Install
curl -sS https://webinstall.dev/k9s | bash
# Run
k9s
# Commands
# :ns - namespace
# :po - pods
# :svc - services
# :dp - deployments

Answer:

Terminal window
# Install
# Download from lenside.com
# Connect to cluster
# Add cluster via kubeconfig
# Features
# Visual interface
# Resource management
# Terminal integration

Answer:

Terminal window
# Install
# Download from GitHub releases
# Run
octant
# Or as plugin in Lens
# Enable in settings

Q821: How do you configure SELinux policies?

Section titled “Q821: How do you configure SELinux policies?”

Answer:

Terminal window
# Install policy tools
apt install policycoreutils-devel selinux-policy-dev
# Create module
# myapp.te
module myapp 1.0;
require {
type http_t;
type var_t;
class file { read write };
}
allow http_t var_t:file { read write };
# Compile
checkmodule -M -m -o myapp.mod myapp.te
# Install
semodule -i myapp.pp

Q822: How do you create AppArmor profiles?

Section titled “Q822: How do you create AppArmor profiles?”

Answer:

Terminal window
# Generate profile
aa-genprof /usr/bin/myapp
# Enforce
aa-enforce /usr/bin/myapp
# Monitor in complain
aa-complain /usr/bin/myapp
# Check status
aa-status

Q823: How do you implement full disk encryption?

Section titled “Q823: How do you implement full disk encryption?”

Answer:

Terminal window
# During installation
# Use LVM with LUKS
# After installation
# Use dm-crypt
cryptsetup luksFormat /dev/sdb1
# Backup header
cryptsetup luksHeaderBackup /dev/sdb1 --header-backup-file /root/luks-header.img

Answer:

Terminal window
# Install signed kernel
# Use UEFI secure boot
# Enroll keys
# MOK (Machine Owner Key)
mokutil --import key.der
# Verify
mokutil --list-enrolled
sbverify --list /boot/vmlinuz

Answer:

Terminal window
# Install TPM tools
apt install tpm2-tools
# Create key
tpm2_createprimary -G rsa -o primary.key
# Seal
tpm2_unseal -c primary.key -o unsealed.key -i sealed.data
# Unseal
tpm2_unseal -c primary.key -i sealed.data

Q826: How do you configure secure container runtime?

Section titled “Q826: How do you configure secure container runtime?”

Answer:

Terminal window
# Use gVisor
# Install runsc
# Use Kata Containers
# Install kata-runtime
# Use Rootless Podman
podman run --security-opt seccomp=default --security-opt no-new-privileges nginx

Q827: How do you implement network policies in Kubernetes?

Section titled “Q827: How do you implement network policies in Kubernetes?”

Answer:

# Default deny
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress

Answer:

Terminal window
# Use RBAC
# Create ServiceAccount with minimal permissions
# Enable RBAC
--authorization-mode=RBAC
# Use TLS
# Ensure all traffic uses TLS
# Network policies
# Limit access to API server

Answer:

Terminal window
# Use TLS
# Enable encryption at rest
# Use separate etcd cluster
# Enable authentication
# Backup etcd
ETCDCTL_API=3 etcdctl snapshot save backup.db \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key

Q830: How do you implement secrets management in K8s?

Section titled “Q830: How do you implement secrets management in K8s?”

Answer:

# Use external-secrets
apiVersion: external-secrets.io/v1beta1
kind: ClusterSecretStore
metadata:
name: vault-backend
spec:
provider:
vault:
server: "https://vault:8200"
path: "secret"
version: "v2"
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: mysecret
spec:
refreshInterval: 1h
secretStoreRef:
name: vault-backend
kind: ClusterSecretStore
target:
name: mysecret
data:
- secretKey: api_key
remoteRef:
key: myapp/api_key

Answer:

Terminal window
# Use bpfcc-tools
apt install bpfcc-tools
# CPU analysis
funccount-bpfcc 't:kernel_function'
# I/O analysis
biolatency-bpfcc
# Network analysis
tcplife-bpfcc

Answer:

Terminal window
# Install
git clone https://github.com/brendangregg/FlameGraph.git
# Generate
# CPU profile
perf record -F 99 -p PID -g
perf script | ./FlameGraph/stackcollapse-perf.pl | ./FlameGraph/flamegraph.pl > flame.svg
# Memory
./flamegraph.pl --title="Memory Profile" < profile.txt > memory.svg

Answer:

Terminal window
# bpftrace examples
# Count system calls
bpftrace -e 'tracepoint:syscalls:sys_enter_* { @[comm] = count(); }'
# Measure latency
bpftrace -e 'kprobe:do_nice { @start[comm] = nsecs(); } kretprobe:do_nice /@start[comm]/ { @ns[comm] = quantize(nsecs() - @start[comm]); }'
# Network connections
bpftrace -e 'kprobe:tcp_connect { @[comm] = count(); }'

Q834: How do you configure kernel tuning for low latency?

Section titled “Q834: How do you configure kernel tuning for low latency?”

Answer:

/etc/sysctl.conf
# Network
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728
# Kernel
kernel.sched_latency_ns = 10000000
kernel.sched_min_granularity_ns = 1000000
kernel.sched_wakeup_granularity_ns = 1000000
# Apply
sysctl -p

Answer:

Terminal window
# Install RT kernel
apt install linux-image-rt-*
# Configure
# /etc/default/rtirq
RTIRQ_RESET_ALL=on
RTIRQ_POLLING="rtc"
# CPU isolation
# Add to GRUB: isolcpus=1,2,3

Answer:

Terminal window
# Install DPDK
# Download from dpdk.org
# Setup
export DPDK_DIR=/path/to/dpdk
export RTE_SDK=$DPDK_DIR
export RTE_TARGET=x86_64-native-linuxapp-gcc
# Build
make config T=$RTE_TARGET
make -j$(nproc)
# Huge pages
echo 1024 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages

Answer:

Terminal window
# Install
apt install rdma-core
# Check devices
rdma link
# Configure
# Use Mellanox or Intel RDMA cards
# Test
ib_write_bw -d mlx5_0 -a

Answer:

Terminal window
# Enable in BIOS
# Enable in kernel
# Add to GRUB: intel_iommu=on
# Configure
echo 2 > /sys/bus/pci/devices/0000\:01\:00.0/sriov_numvfs
# Verify
lspci | grep -i virtual
# Assign to VM
virsh attach-interface --domain vm --type hostdev --source 0000:01:00.2 --managed

Answer:

Terminal window
# Check NUMA
numactl --hardware
# Pin process
numactl --cpunodebind=0 --membind=0 process
# Use libnuma
# In code
numa_run_on_node(0);
numa_tonodememory(0, size);

Answer:

Terminal window
# Check
cat /proc/meminfo | grep Huge
# Configure
echo 256 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
# Use in application
# mmap with MAP_HUGETLB flag
# For Java
# -XX:+UseLargePages

Q841: How do you configure NVMe optimization?

Section titled “Q841: How do you configure NVMe optimization?”

Answer:

Terminal window
# Check
nvme list
nvme smart-log /dev/nvme0
# Optimize
# Use noop or deadline scheduler
echo none > /sys/block/nvme0n1/queue/scheduler
# Increase queue depth
echo 1024 > /sys/block/nvme0n1/queue/nr_requests

Answer:

Terminal window
# Check
ndctl list
# Create namespace
ndctl create-namespace
# Mount
# As DAX (Direct Access)
mkfs.ext4 -F /dev/pmem0
mount -o dax /dev/pmem0 /mnt/pmem
# Use in code
# Use libpmem

Q843: How do you configure storage class for performance?

Section titled “Q843: How do you configure storage class for performance?”

Answer:

# Kubernetes StorageClass
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: fast
provisioner: kubernetes.io/gce-pd
parameters:
type: pd-ssd
replication-type: regional-pd
volumeBindingMode: WaitForFirstConsumer

Q844: How do you implement distributed storage?

Section titled “Q844: How do you implement distributed storage?”

Answer:

Terminal window
# Use Ceph
# Install
ceph-deploy install node1 node2 node3
ceph-deploy mon create node1
ceph-deploy osd create node1:/dev/sdb
# Create pool
ceph osd pool create mypool 100
# Use
rbd create mypool/image --size 10G

Answer:

Terminal window
# Install
wget https://dl.min.io/server/minio/release/linux-amd64/minio
chmod +x minio
# Start
./minio server /data
# Use S3 API
mc alias set myminio http://localhost:9000 accesskey secretkey
mc mb myminio/mybucket

Q846: How do you use Rook/Ceph in Kubernetes?

Section titled “Q846: How do you use Rook/Ceph in Kubernetes?”

Answer:

Terminal window
# Install Rook
kubectl apply -f https://raw.githubusercontent.com/rook/rook/master/cluster/examples/kubernetes/ceph/common.yaml
kubectl apply -f https://raw.githubusercontent.com/rook/rook/master/cluster/examples/kubernetes/ceph/cluster.yaml
# Create PVC
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mypvc
spec:
storageClassName: rook-ceph-block
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi

Answer:

apiVersion: v1
kind: PersistentVolume
metadata:
name: local-pv
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
storageClassName: local-storage
local:
path: /mnt/disks/ssd1
nodeAffinity:
required:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- node-1

Answer:

Terminal window
# Install NFS provisioner
helm install nfs-server stable/nfs-server-provisioner
# Create PVC
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mypvc
spec:
storageClassName: nfs
accessModes:
- ReadWriteMany
resources:
requests:
storage: 1Gi

Answer:

# Kubernetes ResourceQuota
apiVersion: v1
kind: ResourceQuota
metadata:
name: storage-quota
spec:
hard:
requests.storage: 100Gi
persistentvolumeclaims: "10"

Q850: How do you implement data replication?

Section titled “Q850: How do you implement data replication?”

Answer:

Terminal window
# Use GlusterFS
gluster volume create replica 2 \
node1:/brick1/brick \
node2:/brick1/brick
# Use Ceph
ceph osd pool create mypool 100 100
ceph osd pool set mypool size 3
# Use Rook
# Configure in CephCluster CRD
spec:
storage:
useAllNodes: true
useAllDevices: true
deviceFilter: sd*

Answer:

Terminal window
# Install Cilium CLI
curl -sL https://raw.githubusercontent.com/cilium/cilium-cli/main/install.sh | bash
# Install
cilium install
# Enable Hubble
cilium hubble enable
# Check status
cilium status
cilium hubble ui

Answer:

Terminal window
# Install Calico
kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml
# Enable eBPF mode
calicoctl patch felixdefault -p '{"spec":{"bpfLogLevel":"info","bpfEnabled":true}}'
# Check
calicoctl node status

Q853: How do you configure network metrics?

Section titled “Q853: How do you configure network metrics?”

Answer:

Terminal window
# Use Prometheus with Cilium
cilium metrics enable
# Or use Weave Scope
kubectl apply -f https://cloud.weave.works/launch/k8s/weavescope.yaml
# Or use kube-state-metrics
kubectl apply -f https://github.com/kubernetes/kube-state-metrics/archive/master/examples/standard/deployment.yaml

Answer:

Terminal window
# Install Istio
istioctl install --set profile=demo
# Enable sidecar injection
kubectl label namespace default istio-injection=enabled
# Deploy
kubectl apply -f deployment.yaml
# View traffic
istioctl dashboard kiali

Answer:

envoy.yaml
static_resources:
listeners:
- name: listener_0
address:
socket_address:
address: 0.0.0.0
port_value: 8080
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: ingress_http
route_config:
name: local_route
virtual_hosts:
- name: local_service
domains: ["*"]
routes:
- match:
prefix: "/"
route:
cluster: my_service
clusters:
- name: my_service
type: STATIC
lb_policy: ROUND_ROBIN
hosts:
- socket_address:
address: 127.0.0.1
port_value: 80

Answer:

# CoreDNS config
apiVersion: v1
kind: ConfigMap
metadata:
name: coredns
namespace: kube-system
data:
Corefile: |
.:53 {
errors
health
kubernetes cluster.local in-addr.arpa ip6.arpa {
pods insecure
fallthrough in-addr.arpa ip6.arpa
}
forward . /etc/resolv.conf
prometheus :9153
cache 30
}

Q857: How do you implement ingress controller?

Section titled “Q857: How do you implement ingress controller?”

Answer:

Terminal window
# Install NGINX Ingress
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.5.1/deploy/static/provider/cloud/deploy.yaml
# Create Ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: myapp
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: myapp
port:
number: 80

Answer:

# MetalLB
apiVersion: v1
kind: ConfigMap
metadata:
namespace: metallb-system
name: config
data:
config: |
address-pools:
- name: default
protocol: layer2
addresses:
- 192.168.1.240-192.168.1.250
# Service
apiVersion: v1
kind: Service
metadata:
name: myapp
spec:
type: LoadBalancer
selector:
app: myapp
ports:
- port: 80
targetPort: 80

Answer:

Terminal window
# CoreDNS
# Use Kubernetes DNS
# myservice.mynamespace.svc.cluster.local
# External DNS
kubectl apply -f https://github.com/kubernetes-sigs/external-dns/master/releases/download/v0.12.0/provider.yaml
# Configure
apiVersion: v1
kind: ConfigMap
metadata:
name: external-dns
data:
config.yaml: |
provider: cloudflare
source: service
policy: sync

Answer:

# Istio mTLS
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: istio-system
spec:
mtls:
mode: STRICT
# Or use Linkerd
# Linkerd automatically mTLS
linkerd jaeger | kubectl apply -f -

Answer:

Terminal window
# Use Prometheus + Grafana + Alertmanager
# Install via Helm
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/kube-prometheus-stack
# Access
kubectl port-forward svc/prometheus-grafana 3000

Answer:

# Prometheus Alert
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: myapp-alerts
spec:
groups:
- name: myapp
rules:
- alert: HighMemory
expr: (container_memory_working_set_bytes / container_spec_memory_limit_bytes) > 0.8
for: 5m
labels:
severity: warning
annotations:
summary: "High memory usage"

Q863: How do you implement disaster recovery?

Section titled “Q863: How do you implement disaster recovery?”

Answer:

Terminal window
# Backup etcd
ETCDCTL_API=3 etcdctl snapshot save /backup/etcd.db \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key
# Restore
ETCDCTL_API=3 etcdctl snapshot restore /backup/etcd.db

Answer:

Terminal window
# Install ArgoCD
kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
# Create application
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: myapp
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/myorg/myapp
targetRevision: HEAD
path: deploy
destination:
server: https://kubernetes.default.svc
namespace: default
syncPolicy:
automated:
prune: true
selfHeal: true

Q865: How do you implement chaos engineering?

Section titled “Q865: How do you implement chaos engineering?”

Answer:

Terminal window
# Install Litmus
kubectl apply -f https://litmuschaos.github.io/litmus/2.0.0/litmus-2.0.0.yaml
# Create ChaosEngine
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosEngine
metadata:
name: pod-kill
spec:
appinfo:
appns: default
applabel: "app=myapp"
chaosServiceAccount: litmus-admin
experiments:
- name: pod-kill

Q866: How do you set up supply chain security?

Section titled “Q866: How do you set up supply chain security?”

Answer:

Terminal window
# Use Sigstore Cosign
cosign generate-key-pair
# Sign images
cosign sign --key cosign.key myregistry.com/myimage:v1.0
# Verify
cosign verify --key cosign.pub myregistry.com/myimage:v1.0
# Use in CI/CD
- name: Verify
run: |
cosign verify --key cosign.pub $IMAGE

Answer:

Terminal window
# Use OpenTelemetry
# Install collector
kubectl apply -f https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.50.0/otelcol.yaml
# Instrument application
# Add OpenTelemetry SDK to application
# Use Jaeger for tracing
kubectl apply -f https://github.com/jaegertracing/jaeger-operator/releases/latest/download/jaeger.yaml

Q868: How do you configure cost optimization?

Section titled “Q868: How do you configure cost optimization?”

Answer:

Terminal window
# Use Kubecost
kubectl apply -f https://github.com/kubecost/cost-analyzer-helm-chart/releases/latest/download/kubecost.yaml
# Check costs
# Access dashboard
# Use spot instances
# Configure node pools with spot/preemptible instances
# Right-size resources
# Use VPA (Vertical Pod Autoscaler)

Q869: How do you implement compliance as code?

Section titled “Q869: How do you implement compliance as code?”

Answer:

Terminal window
# Use OPA/Conftest
# policy.rego
package main
deny[msg] {
input.kind == "Deployment"
not input.spec.template.spec.securityContext
msg = "Deployment must have securityContext"
}
# Test
conftest test deployment.yaml

Q870: How do you set up policy enforcement?

Section titled “Q870: How do you set up policy enforcement?”

Answer:

Terminal window
# Use OPA Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper-library/master/library/pod-security-policy/privileged-containers/template.yaml
# Create constraint
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPrivilegedContainer
metadata:
name: psp-privileged-container
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]

Answer:

Terminal window
# Aliases
alias k=kubectl
alias kgp='kubectl get pods'
alias kga='kubectl get all'
alias kdp='kubectl describe pod'
alias klf='kubectl logs -f'
# Contexts
kubectl config get-contexts
kubectl config use-context production
# Quick access
kubectl run nginx --image=nginx --restart=Never --dry-run=client -o yaml > nginx.yaml

Answer:

Terminal window
# Common commands
helm install myrelease stable/nginx
helm upgrade myrelease stable/nginx
helm rollback myrelease 1
# Template
helm template myrelease stable/nginx
# Repo management
helm repo add stable https://charts.helm.sh/stable
helm repo update
helm search repo nginx

Answer:

Terminal window
# Check events
kubectl get events --sort-by='.lastTimestamp'
# Check logs
kubectl logs -f deployment/myapp
kubectl logs -f deployment/myapp --previous
# Describe
kubectl describe pod myapp-pod
# Exec into container
kubectl exec -it myapp-pod -- /bin/bash

Q874: How do you secure containers in production?

Section titled “Q874: How do you secure containers in production?”

Answer:

Terminal window
# Use read-only root filesystem
securityContext:
readOnlyRootFilesystem: true
# Drop capabilities
securityContext:
capabilities:
drop:
- ALL
# Run as non-root
securityContext:
runAsNonRoot: true
runAsUser: 10000
# Use image scanning
trivy image nginx:latest

Q875: How do you optimize Kubernetes costs?

Section titled “Q875: How do you optimize Kubernetes costs?”

Answer:

Terminal window
# Use Resource Limits
resources:
limits:
cpu: "500m"
memory: "512Mi"
requests:
cpu: "200m"
memory: "256Mi"
# Use VPA
# Vertical Pod Autoscaler
# Use HPA
# Horizontal Pod Autoscaler
# Use cluster autoscaler
# Enable in cloud provider

Q876: How do you handle state in Kubernetes?

Section titled “Q876: How do you handle state in Kubernetes?”

Answer:

Terminal window
# Use StatefulSets
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: myapp
spec:
serviceName: myapp
replicas: 3
selector:
matchLabels:
app: myapp
template:
spec:
containers:
- name: myapp
image: myapp:latest
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi

Q877: How do you implement canary deployments?

Section titled “Q877: How do you implement canary deployments?”

Answer:

# Using Istio
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: myapp
spec:
hosts:
- myapp
http:
- route:
- destination:
host: myapp
subset: v1
weight: 90
- destination:
host: myapp
subset: v2
weight: 10

Q878: How do you implement blue-green deployments?

Section titled “Q878: How do you implement blue-green deployments?”

Answer:

Terminal window
# Create blue deployment
kubectl apply -f blue-deployment.yaml
# Switch service
kubectl patch service myapp -p '{"spec":{"selector":{"version":"blue"}}}'
# Or use Ingress
# Update ingress to point to new version

Q879: How do you implement rolling updates?

Section titled “Q879: How do you implement rolling updates?”

Answer:

Terminal window
# Update deployment
kubectl set image deployment/myapp myapp=myapp:v2
# Check rollout status
kubectl rollout status deployment/myapp
# Pause rollout
kubectl rollout pause deployment/myapp
# Resume
kubectl rollout resume deployment/myapp
# Rollback
kubectl rollout undo deployment/myapp

Answer:

# Liveness probe
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
failureThreshold: 3
# Readiness probe
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 3
# Startup probe
startupProbe:
httpGet:
path: /healthz
port: 8080
failureThreshold: 30
periodSeconds: 10

Answer:

Terminal window
# Base kustomization
# kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml
# Overlay
# production/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
bases:
- ../base
patches:
- patch.yaml
# Apply
kubectl apply -k production/

Answer:

skaffold.yaml
apiVersion: skaffold/v2beta26
kind: Config
build:
artifacts:
- image: myapp
deploy:
kubectl:
manifests:
- k8s/*.yaml
portForward:
- resourceType: deployment
resourceName: myapp
port: 8080
localPort: 8080

Answer:

# Tiltfile
docker_build('myapp', '.')
k8s_yaml('k8s/deployment.yaml')
k8s_resource('myapp', port_forwards=8080)

Q884: How do you implement GitOps workflows?

Section titled “Q884: How do you implement GitOps workflows?”

Answer:

Terminal window
# 1. Store Kubernetes manifests in Git
git add k8s/
git commit -m "Update deployment"
git push
# 2. Use GitOps tool (ArgoCD/Flux)
# 3. Tool syncs Git -> Cluster
# 4. Automatic drift detection
# Best practices
# - Use separate repo for GitOps
# - Branch by environment
# - Require PRs for changes

Answer:

Terminal window
# Use SOPS
# Install
go install github.com/mozilla/sops@latest
# Encrypt
sops -e secrets.yaml > secrets.encrypted.yaml
# Decrypt
sops -d secrets.encrypted.yaml
# Or use SealedSecrets
# Or use external-secrets-operator

Q886: How do you implement backup for K8s?

Section titled “Q886: How do you implement backup for K8s?”

Answer:

Terminal window
# Use Velero
# Install
kubectl apply -f https://raw.githubusercontent.com/vmware-tanzu/velero/main/install/v1.10.0/velero.yaml
# Backup
velero backup create mybackup --include-namespaces default
# Restore
velero restore create --from-backup mybackup
# Schedule
velero schedule create daily --schedule="0 0 * * *" --include-namespaces default

Answer:

Terminal window
# Install Service Catalog
kubectl apply -f https://raw.githubusercontent.com/kubernetes-sigs/service-catalog/master/charts/service-catalog/templates/service-catalog-apiserver.yaml
# Provision service
# Use ServiceBinding
apiVersion: servicecatalog.k8s.io/v1beta1
kind: ServiceBinding
metadata:
name: myapp-binding
spec:
serviceInstanceRef:
name: my-service
secretName: myapp-secret

Answer:

Terminal window
# Use Federation
# Or use ArgoCD with multiple clusters
# Add cluster to ArgoCD
argocd cluster add context-name
# Deploy to all clusters
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: myapp
spec:
destination:
server: https://kubernetes.default.svc
# Or use ClusterResourceQuota

Answer:

Terminal window
# Kubernetes upgrade
# 1. Upgrade control plane
kubeadm upgrade plan
kubeadm upgrade apply v1.26.0
# 2. Upgrade kubelet
apt-get install kubelet=1.26.0-*
# 3. Upgrade worker nodes
kubectl drain node-1
apt-get install kubelet=1.26.0-*
kubectl uncordon node-1

Q890: How do you implement security scanning?

Section titled “Q890: How do you implement security scanning?”

Answer:

Terminal window
# Container scanning
trivy image nginx:latest
docker scout cves myimage
# K8s security scan
kubescape scan --severity threshold
# Runtime security
falco --help

Q891: How do you configure audit logging in K8s?

Section titled “Q891: How do you configure audit logging in K8s?”

Answer:

/etc/kubernetes/audit-policy.yaml
# Enable audit
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: RequestResponse
resources:
- group: ""
resources: ["pods"]
- level: Metadata
resources:
- group: ""
resources: ["pods/log", "pods/status"]
# Configure API server
# --audit-policy-file=/etc/kubernetes/audit-policy.yaml
# --audit-log-path=/var/log/kubernetes/audit

Answer:

# Pod Security Standards
# Restricted
apiVersion: v1
kind: Pod
metadata:
name: restricted-pod
spec:
securityContext:
seccompProfile:
type: RuntimeDefault
containers:
- name: app
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL

Answer:

# Allow specific traffic
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-allow
spec:
podSelector:
matchLabels:
app: api
ingress:
- from:
- podSelector:
matchLabels:
app: web
ports:
- protocol: TCP
port: 8080

Answer:

# NGINX Ingress rate limiting
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: myapp
annotations:
nginx.ingress.kubernetes.io/limit-rps: "100"
nginx.ingress.kubernetes.io/limit-connections: "50"
spec:
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: myapp
port:
number: 80

Answer:

apiVersion: v1
kind: ResourceQuota
metadata:
name: myquota
spec:
hard:
requests.cpu: "10"
requests.memory: 20Gi
limits.cpu: "20"
limits.memory: 40Gi
pods: "20"
services: "10"
persistentvolumeclaims: "5"

Answer:

apiVersion: v1
kind: LimitRange
metadata:
name: mylimits
spec:
limits:
- max:
cpu: "4"
memory: 8Gi
min:
cpu: 100m
memory: 128Mi
default:
cpu: 500m
memory: 1Gi
defaultRequest:
cpu: 200m
memory: 512Mi
type: Container

Q897: How do you use pod disruption budgets?

Section titled “Q897: How do you use pod disruption budgets?”

Answer:

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: myapp-pdb
spec:
minAvailable: 2
selector:
matchLabels:
app: myapp

Q898: How do you implement priority classes?

Section titled “Q898: How do you implement priority classes?”

Answer:

apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: high-priority
value: 1000000
globalDefault: false
description: "Critical workloads"
# Use in pod
priorityClassName: high-priority

Answer:

# Restart policy
# Always, OnFailure, Never
# Liveness probe
livenessProbe:
httpGet:
path: /healthz
port: 8080
failureThreshold: 3
periodSeconds: 10
# Resources
resources:
requests:
memory: "256Mi"
cpu: "200m"
limits:
memory: "512Mi"
cpu: "500m"

Q900: How do you implement graceful shutdown?

Section titled “Q900: How do you implement graceful shutdown?”

Answer:

Terminal window
# PreStop hook
lifecycle:
preStop:
exec:
command:
- /bin/sh
- -c
- "sleep 10 && kill -SIGTERM 1"
# SIGTERM handling
# In application, handle SIGTERM
# Save state, close connections, graceful shutdown

Answer:

Terminal window
# Use TLS for etcd
# Enable encryption at rest
# Use separate etcd cluster
# Enable authentication
# Backup regularly

Q902: How do you configure API server security?

Section titled “Q902: How do you configure API server security?”

Answer:

Terminal window
# Use RBAC
# Enable admission controllers
# Use TLS for all traffic
# Limit network access
# Use API aggregation
# Secure flags
--authorization-mode=RBAC
--enable-admission-plugins=NodeRestriction
--encrypt-provider-config=encryption-config.yaml

Q903: How do you implement pod security policies?

Section titled “Q903: How do you implement pod security policies?”

Answer:

apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: restricted
spec:
privileged: false
seLinux:
rule: RunAsAny
runAsUser:
rule: MustRunAsNonRoot
fsGroup:
rule: RunAsAny
volumes:
- 'secret'
- 'configMap'
hostNetwork: false
hostPID: false
hostIPC: false

Answer:

/var/lib/kubelet/config.yaml
# Configure kubelet
authentication:
anonymous:
enabled: false
webhook:
enabled: true
authorization:
mode: Webhook
# Use Node Authorizer
# Enable NodeRestriction admission plugin

Q905: How do you implement network segmentation in K8s?

Section titled “Q905: How do you implement network segmentation in K8s?”

Answer:

# Network policies
# Deny all by default
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress

Q906: How do you secure container registry?

Section titled “Q906: How do you secure container registry?”

Answer:

Terminal window
# Use TLS
# Enable authentication
# Use scanning tools
# Implement access control
# Use signed images
# Regular rotation of credentials
# Use Harbor with vulnerability scanning
# Use Notary for content trust

Q907: How do you implement runtime security?

Section titled “Q907: How do you implement runtime security?”

Answer:

Terminal window
# Use Falco
kubectl apply -f https://raw.githubusercontent.com/falcosecurity/falco/master/integrations/k8s-using-daemonset/falco-daemonset-configmap.yaml
# Rules
# Detect suspicious activities
# File access, process execution, network calls

Answer:

Terminal window
# Use dedicated service accounts
# Limit permissions
# Disable auto-mount of tokens
# Use RBAC
# Best practices
# Create SA per application
# Don't use default SA
# Rotate tokens regularly

Q909: How do you implement secrets encryption?

Section titled “Q909: How do you implement secrets encryption?”

Answer:

encryption-config.yaml
apiVersion: v1
kind: Secret
metadata:
name: aes-key
data: <base64-key>
# Configure API server
# --encryption-provider-config=encryption-config.yaml
# Verify
# Check etcd directly
etcdctl get /registry/secrets/default/secret-name

Q910: How do you secure etcd communication?

Section titled “Q910: How do you secure etcd communication?”

Answer:

Terminal window
# Use TLS
# etcd-ca.pem
# etcd-server.pem
# etcd-client.pem
# Configure API server
# --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt
# --etcd-certfile=/etc/kubernetes/pki/etcd/server.crt
# --etcd-keyfile=/etc/kubernetes/pki/etcd/server.key

Q911: How do you implement cluster disaster recovery?

Section titled “Q911: How do you implement cluster disaster recovery?”

Answer:

Terminal window
# 1. Regular etcd backups
ETCDCTL_API=3 etcdctl snapshot save /backup/etcd.db
# 2. Regular cluster state backup
# Backup all CRDs, Deployments, etc.
# 3. Document recovery procedures
# 4. Test recovery regularly
# 5. Use cluster federation for multi-cluster

Q912: How do you secure Kubernetes dashboard?

Section titled “Q912: How do you secure Kubernetes dashboard?”

Answer:

Terminal window
# Don't expose publicly
# Use RBAC
# Enable HTTPS
# Use token authentication
# Enable audit logging
# Restrict IP access
# Best practice
# Use kubectl proxy or VPN

Q913: How do you implement supply chain security?

Section titled “Q913: How do you implement supply chain security?”

Answer:

Terminal window
# Use SBOM (Software Bill of Materials)
# Sign images with Cosign
# Use in-toto attestations
# Implement SLSA compliance
# Tools
# Syft (generate SBOM)
# Cosign (sign images)
# Grafeas (store attestations)

Q914: How do you secure the control plane?

Section titled “Q914: How do you secure the control plane?”

Answer:

Terminal window
# Use separate networks
# Enable RBAC
# Use TLS everywhere
# Encrypt etcd
# Limit etcd access
# Use admission controllers
# Enable audit logging
# Network policies
# Isolate control plane from workloads

Q915: How do you implement defense in depth?

Section titled “Q915: How do you implement defense in depth?”

Answer:

Terminal window
# Layer 1: Network
# Firewalls, WAF, network policies
# Layer 2: Node
# Hardened OS, SELinux/AppArmor
# Layer 3: Container
# Read-only rootfs, non-root user, capabilities
# Layer 4: Application
# Security scanning, secure coding
# Layer 5: Data
# Encryption, access control

Answer:

Terminal window
# Regular scanning
# Use Trivy, Snyk, Clair
# Patch quickly
# Automate updates
# Use base image scanning
# Scan dependencies
# Quarantine vulnerable images
# Use image policies

Answer:

Terminal window
# Use OpenSCAP
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis /usr/share/xml/scap/ssg/content/ssg-ubuntu2004-ds.xml
# Use Kyverno
# Policy-as-code
# Document compliance
# Regular audits
# Automated checks in CI/CD

Answer:

Terminal window
# Secrets management
# Use Vault, AWS Secrets Manager
# Access control
# Principle of least privilege
# Image scanning
# Block vulnerable images
# Signed commits
# Require code review
# Supply chain security
# Use SLSA

Q919: How do you implement incident response?

Section titled “Q919: How do you implement incident response?”

Answer:

Terminal window
# 1. Detection
# Monitoring, alerting
# 2. Containment
# Isolate affected systems
# 3. Investigation
# Logs, forensics
# 4. Recovery
# Restore from backup
# 5. Lessons learned
# Post-mortem
# Runbooks
# Practice regularly

Q920: How do you secure Kubernetes networking?

Section titled “Q920: How do you secure Kubernetes networking?”

Answer:

# Use NetworkPolicies
# Default deny
# Allow explicit
# Use service mesh
# Examples
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: web-to-api
spec:
podSelector:
matchLabels:
app: api
ingress:
- from:
- podSelector:
matchLabels:
app: web

Answer:

Terminal window
# Enable audit
# Configure audit policy
# --audit-policy-file=/path/to/policy.yaml
# Review logs
# Store in secure location
# Use SIEM integration
# Regular review

Q922: How do you implement secrets rotation?

Section titled “Q922: How do you implement secrets rotation?”

Answer:

Terminal window
# Use external-secrets-operator
# Rotate regularly
# Use key management services
# Kubernetes
# Automatic token rotation
# Use short-lived tokens
# Best practice
# Rotate every 90 days
# Automate the process

Q923: How do you secure container orchestration?

Section titled “Q923: How do you secure container orchestration?”

Answer:

Terminal window
# Use RBAC
# Network policies
# Pod security policies
# Secrets management
# Image scanning
# Runtime security
# Regular updates
# Tools
# Kube-bench
# Kubescape
# Kyverno

Q924: How do you handle compliance frameworks?

Section titled “Q924: How do you handle compliance frameworks?”

Answer:

Terminal window
# PCI-DSS
# Use specific profiles
# HIPAA
# GDPR
# SOC 2
# ISO 27001
# Use OpenSCAP
# Use policy engines
# Automate compliance checks

Q925: How do you implement zero trust in K8s?

Section titled “Q925: How do you implement zero trust in K8s?”

Answer:

Terminal window
# mTLS everywhere
# Service mesh
# Short-lived certificates
# Regular rotation
# Network policies
# Microsegmentation
# Verify every request
# Use identity-based access
# Continuous verification

Answer:

Terminal window
# Test in staging
# Use canary
# Backup first
# Document rollback plan
# Monitor during upgrade
# Quick rollback if issues
# Best practice
# Upgrade regularly (quarterly)
# Test applications

Q927: How do you secure cloud-native apps?

Section titled “Q927: How do you secure cloud-native apps?”

Answer:

Terminal window
# Security scanning in CI/CD
# Use signed images
# Secrets management
# Secure coding practices
# Regular patching
# Runtime protection
# Tools
# SAST/DAST
# Container scanning
# Dependency scanning

Q928: How do you implement secure defaults?

Section titled “Q928: How do you implement secure defaults?”

Answer:

# Pod security
securityContext:
runAsNonRoot: true
runAsUser: 10000
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
# Network
# Default deny
# Explicit allow
# RBAC
# Least privilege
# No default permissions

Answer:

Terminal window
# Use TLS 1.3
# mTLS in service mesh
# Certificate management
# Use strong ciphers
# In Kubernetes
# Use Istio/Linkerd
# Configure Ingress TLS
# Service mesh mTLS

Answer:

Terminal window
# Use encryption
# LUKS for volumes
# Database encryption
# Use key management
# Kubernetes
# Use CSI drivers with encryption
# Enable encryption at rest
# Rotate keys regularly

Q931: How do you implement access control?

Section titled “Q931: How do you implement access control?”

Answer:

Terminal window
# RBAC
# Create roles
# Bind to users/groups
# Use ServiceAccounts
# Best practices
# Least privilege
# Regular review
# Audit access
# Use external identity
# LDAP, SAML, OIDC

Answer:

Terminal window
# Use RBAC
# Limit access
# Use TLS
# Enable audit logging
# Use admission controllers
# Don't expose publicly
# Use VPN/bastion
# Use API aggregation
# Rate limiting

Answer:

Terminal window
# Use minimal OS
# Apply security patches
# Use CIS benchmarks
# Enable firewall
# Restrict access
# Node hardening
# Disable unnecessary services
# Use SELinux/AppArmor
# Regular updates

Q934: How do you implement secure bootstrapping?

Section titled “Q934: How do you implement secure bootstrapping?”

Answer:

Terminal window
# Use TPM
# Secure boot
# Measure boot
# Use remote attestation
# Kubernetes
# Use encrypted secrets
# Use sealed secrets
# Use HSM for keys

Answer:

Terminal window
# Use SBOM
# Sign artifacts
# Verify signatures
# Use trusted registries
# Regular scanning
# Implement SLSA
# Build integrity
# Provenance
# Tools
# Cosign
# Grafeas
# in-toto

Q936: How do you handle security incidents?

Section titled “Q936: How do you handle security incidents?”

Answer:

Terminal window
# Detection
# Alerts, monitoring
# Containment
# Isolate affected pods
# Block malicious traffic
# Investigation
# Logs, traces
# Recovery
# Restore from backup
# Patch vulnerabilities
# Post-incident
# Lessons learned
# Update runbooks

Answer:

# Use namespaces
# Resource quotas
# Network policies
# Node isolation
# Pod security policies
# RBAC per tenant
# Quotas per team
# Separate etcd
# Encrypted namespaces

Answer:

Terminal window
# Use Vault
# Use external-secrets-operator
# Use SealedSecrets
# Use AWS Secrets Manager
# Best practices
# Rotate regularly
# Audit access
# Use encryption
# Short-lived tokens

Answer:

Terminal window
# Multiple layers
# Network, host, container, app
# Monitoring
# Real-time alerts
# Quick response
# Automated blocking
# Regular testing
# Pen testing
# Red team
# Updates
# Patch quickly

Q940: How do you secure container runtime?

Section titled “Q940: How do you secure container runtime?”

Answer:

Terminal window
# Use rootless containers
# Drop capabilities
# Read-only rootfs
# No privileged mode
# Seccomp/AppArmor
# Runtime security
# Falco, Sysdig
# Isolation
# gVisor, Kata Containers
# User namespaces

Q941: How do you implement continuous security?

Section titled “Q941: How do you implement continuous security?”

Answer:

Terminal window
# Security in CI/CD
# Scan images
# Scan dependencies
# Policy enforcement
# Runtime
# Monitor behavior
# Detect threats
# Compliance
# Regular audits
# Automated checks

Answer:

Terminal window
# Use SBOM
# Sign images
# Verify signatures
# Use trusted sources
# Implement SLSA
# Level 1: Build provenance
# Level 2: Hosted build
# Level 3: Hardened build
# Tools
# Cosign, Notary, in-toto

Q943: How do you secure Kubernetes networking?

Section titled “Q943: How do you secure Kubernetes networking?”

Answer:

Terminal window
# Default deny
# Explicit allow
# Use NetworkPolicies
# Service mesh
# mTLS everywhere
# Encryption
# TLS for ingress
# VPN for internal
# Tools
# Calico, Cilium, Canal

Answer:

Terminal window
# Input validation
# Output encoding
# Authentication
# Authorization
# Session management
# Error handling
# Logging
# Dependencies
# Regular updates
# Scan for CVEs
# Use Snyk, Dependabot

Answer:

Terminal window
# Encryption
# LUKS, dm-crypt
# Access control
# RBAC, ACLs
# Backups
# Encrypted backups
# Offsite storage
# Kubernetes
# CSI encryption
# Secrets encryption
# Encrypted volumes

Answer:

Terminal window
# Use encryption
# mTLS
# Network policies
# Service mesh
# Container isolation
# gVisor, Kata
# User namespaces
# Runtime security
# Falco
# Sysdig

Q947: How do you implement defense in depth?

Section titled “Q947: How do you implement defense in depth?”

Answer:

Terminal window
# Multiple layers
# Perimeter, network, host, app
# Zero trust
# Never trust, always verify
# Least privilege
# Minimal permissions
# Regular assessment
# Penetration testing
# Vulnerability scanning

Q948: How do you secure the control plane?

Section titled “Q948: How do you secure the control plane?”

Answer:

Terminal window
# Use RBAC
# Limit access
# Enable audit logging
# Use TLS
# Network isolation
# Use separate network
# Don't expose publicly
# Updates
# Patch quickly
# Regular updates

Q949: How do you implement compliance automation?

Section titled “Q949: How do you implement compliance automation?”

Answer:

Terminal window
# Use OPA Gatekeeper
# Policy-as-code
# Use Kyverno
# CRD-based policies
# Use Falco
# Runtime policies
# Use OpenSCAP
# Automated scanning
# Integrate in CI/CD

Q950: How do you secure Kubernetes workloads?

Section titled “Q950: How do you secure Kubernetes workloads?”

Answer:

# Pod security context
securityContext:
runAsNonRoot: true
runAsUser: 10000
fsGroup: 2000
# Container security
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL

Answer:

- rule: Terminal shell in container
desc: notice shell activity
condition: container.id != host and proc.name = bash
output: "Shell in container (user=%user.name container=%container.id image=%container.image.repository)"
priority: WARNING
tags: [container, shell]

Answer:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-app-labels
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
labels:
- key: app

Answer:

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-default-resources
spec:
rules:
- name: add-default-resources
match:
resources:
kinds:
- Pod
mutate:
patchStrategicMerge:
spec:
containers:
- resources:
requests:
memory: "256Mi"
cpu: "250m"

Q954: How do you implement immutable infrastructure?

Section titled “Q954: How do you implement immutable infrastructure?”

Answer:

Terminal window
# Use containers
# Don't modify running containers
# Replace, don't patch
# Use GitOps
# Declarative configs
# Version control
# Automated deployments

Answer:

Terminal window
# Use minimal base images
# Multi-stage builds
# No secrets in images
# Scan for vulnerabilities
# Sign images
# Best practices
# Don't run as root
# Use USER directive
# Remove unnecessary tools

Answer:

Terminal window
# Scan images
# Use Trivy in pipeline
# Don't use latest tag
# Use specific versions
# Separate CI/CD from production
# Use dedicated service accounts
# Sign commits
# Require code review
# Use secrets management

Q957: How do you secure Kubernetes secrets?

Section titled “Q957: How do you secure Kubernetes secrets?”

Answer:

Terminal window
# Don't use base64 encoding alone
# Use encryption at rest
# Use external secrets
# HashiCorp Vault
# AWS Secrets Manager
# Rotate regularly
# Audit access
# Use SealedSecrets
# Use SOPS

Q958: How do you implement security scanning?

Section titled “Q958: How do you implement security scanning?”

Answer:

Terminal window
# Container scanning
trivy image myimage:latest
# K8s scanning
kubescape scan
# Code scanning
sonarqube
# Dependency scanning
npm audit
snyk test

Q959: How do you secure the container registry?

Section titled “Q959: How do you secure the container registry?”

Answer:

Terminal window
# Use authentication
# Use TLS
# Scan images
# Use signed images
# Access control
# Role-based
# Regular cleanup
# Remove old images
# Use private registry
# Harbor, Nexus

Q960: How do you implement secure networking?

Section titled “Q960: How do you implement secure networking?”

Answer:

# NetworkPolicy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress

Answer:

Terminal window
# Use RBAC
# Enable TLS
# Use strong authentication
# Don't expose publicly
# Use VPN
# Enable audit logging
# Monitor access
# Use admission controllers
# Limit what can be created

Answer:

Terminal window
# Multiple layers
# Network, host, container
# Monitoring
# Real-time alerts
# Quick response
# Automated blocking
# Regular assessment
# Vulnerability scanning
# Updates
# Patch quickly

Answer:

# Pod Security Standards
# Restricted profile
# Use security contexts
securityContext:
runAsNonRoot: true
readOnlyRootFilesystem: true
# Use NetworkPolicies
# Default deny
# Use Secrets
# External secrets

Answer:

Terminal window
# Use policy engines
# OPA, Kyverno
# Use scanning tools
# OpenSCAP, Kube-bench
# Use audit logging
# Regular reviews
# Automate checks
# In CI/CD pipeline

Answer:

Terminal window
# Use RBAC
# Network policies
# Encrypt etcd
# Enable audit logging
# Update regularly
# Use CIS benchmarks
# Monitor
# Use Falco
# Use secrets management

Answer:

Terminal window
# Verify everything
# Never trust, always verify
# mTLS everywhere
# Short-lived certificates
# Network policies
# Microsegmentation
# Identity-based
# Not IP-based
# Continuous verification

Q967: How do you secure container runtime?

Section titled “Q967: How do you secure container runtime?”

Answer:

Terminal window
# Use rootless
# Drop capabilities
# Read-only rootfs
# Seccomp/AppArmor
# Profile
# Runtime security
# Falco, Sysdig
# Isolation
# gVisor, Kata

Q968: How do you implement supply chain security?

Section titled “Q968: How do you implement supply chain security?”

Answer:

Terminal window
# Use SBOM
# Sign images
# Verify signatures
# SLSA compliance
# Build integrity
# Trusted registries
# Use scanning
# Tools
# Cosign, Syft, Grafeas

Answer:

Terminal window
# Use TLS 1.3
# mTLS in service mesh
# Certificate management
# Use strong ciphers
# Kubernetes
# Istio, Linkerd
# Ingress TLS
# Service mesh

Answer:

Terminal window
# Encryption
# LUKS, dm-crypt
# Key management
# Use KMS
# Kubernetes
# CSI encryption
# Enable at rest
# Rotate keys
# Regular rotation

Q971: How do you implement access control?

Section titled “Q971: How do you implement access control?”

Answer:

Terminal window
# RBAC
# Least privilege
# Service accounts
# Dedicated per app
# Authentication
# OIDC, LDAP
# Regular review
# Audit access
# Use external identity

Answer:

Terminal window
# Use RBAC
# Limit access
# Use TLS
# Enable audit logging
# Admission controllers
# NodeRestriction
# Don't expose publicly
# Use VPN
# Rate limiting

Answer:

Terminal window
# Use minimal OS
# Apply patches
# CIS benchmarks
# Enable firewall
# Use SELinux
# Restrict access
# Regular updates
# Automated patching

Q974: How do you implement secure bootstrapping?

Section titled “Q974: How do you implement secure bootstrapping?”

Answer:

Terminal window
# Use TPM
# Secure boot
# Measure boot
# Remote attestation
# Encrypted secrets
# Sealed secrets
# Use HSM
# Key management

Answer:

Terminal window
# Use SBOM
# Sign artifacts
# Verify signatures
# Use trusted registries
# Implement SLSA
# Build integrity
# Provenance
# Tools
# Cosign, Notary

Q976: How do you handle security incidents?

Section titled “Q976: How do you handle security incidents?”

Answer:

Terminal window
# Detection
# Alerts, monitoring
# Containment
# Isolate pods
# Investigation
# Logs, forensics
# Recovery
# Restore from backup
# Post-incident
# Lessons learned

Answer:

# Use namespaces
# Resource quotas
# Network policies
# Pod security
# RBAC per tenant
# Quotas per team
# Separate etcd
# Encrypted namespaces

Q978: How do you implement secrets management?

Section titled “Q978: How do you implement secrets management?”

Answer:

Terminal window
# Use Vault
# External secrets
# Rotate regularly
# Audit access
# Use encryption
# Short-lived tokens
# Best practices
# Use KMS

Answer:

Terminal window
# Multiple layers
# Network, host, app
# Monitoring
# Real-time alerts
# Quick response
# Automated blocking
# Regular testing
# Pen testing
# Updates
# Patch quickly

Q980: How do you secure container runtime?

Section titled “Q980: How do you secure container runtime?”

Answer:

Terminal window
# Rootless containers
# Drop capabilities
# Read-only rootfs
# No privileged mode
# Seccomp/AppArmor
# Runtime security
# Falco, Sysdig
# Isolation
# gVisor, Kata

Q981: How do you implement continuous security?

Section titled “Q981: How do you implement continuous security?”

Answer:

Terminal window
# Security in CI/CD
# Scan images
# Runtime
# Monitor behavior
# Compliance
# Regular audits
# Automation
# Policy enforcement
# Automated remediation

Answer:

Terminal window
# Use SBOM
# Sign images
# Verify signatures
# Use trusted sources
# SLSA compliance
# Level 1-3
# Tools
# Cosign, Grafeas, in-toto

Q983: How do you secure Kubernetes networking?

Section titled “Q983: How do you secure Kubernetes networking?”

Answer:

Terminal window
# Default deny
# Explicit allow
# Use NetworkPolicies
# Service mesh
# mTLS
# Encryption
# TLS for ingress
# Tools
# Calico, Cilium

Answer:

Terminal window
# Input validation
# Output encoding
# Authentication
# Authorization
# Error handling
# Logging
# Dependencies
# Regular updates
# Scan for CVEs

Answer:

Terminal window
# Encryption
# LUKS, dm-crypt
# Access control
# RBAC, ACLs
# Backups
# Encrypted backups
# Kubernetes
# CSI encryption
# Secrets encryption

Answer:

Terminal window
# Use encryption
# mTLS
# Network policies
# Service mesh
# Container isolation
# gVisor, Kata
# User namespaces
# Runtime security
# Falco

Q987: How do you implement defense in depth?

Section titled “Q987: How do you implement defense in depth?”

Answer:

Terminal window
# Multiple layers
# Perimeter, network, host, app
# Zero trust
# Never trust
# Least privilege
# Minimal permissions
# Regular assessment
# Pen testing
# Updates
# Patch quickly

Q988: How do you secure the control plane?

Section titled “Q988: How do you secure the control plane?”

Answer:

Terminal window
# Use RBAC
# Limit access
# Enable audit logging
# Use TLS
# Network isolation
# Separate network
# Updates
# Patch quickly

Q989: How do you implement compliance automation?

Section titled “Q989: How do you implement compliance automation?”

Answer:

Terminal window
# Use OPA Gatekeeper
# Policy-as-code
# Use Kyverno
# CRD-based
# Use Falco
# Runtime policies
# Use OpenSCAP
# Automated scanning
# Integrate in CI/CD

Q990: How do you secure Kubernetes workloads?

Section titled “Q990: How do you secure Kubernetes workloads?”

Answer:

# Pod security context
securityContext:
runAsNonRoot: true
runAsUser: 10000
fsGroup: 2000
# Container security
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL

Answer:

# Detect container escapes
- rule: Container escape attempt
desc: Detect container escape attempts
condition: (evt.type=unshare and evt.dir=< and proc.name != containerd-shim)
priority: CRITICAL
tags: [container, security]

Q992: How do you implement network policies?

Section titled “Q992: How do you implement network policies?”

Answer:

# Allow from specific namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-from-namespace
spec:
podSelector: {}
ingress:
- from:
- namespaceSelector:
matchLabels:
name: production

Answer:

Terminal window
# Use authentication
# Use TLS
# Scan images
# Use signed images
# Access control
# Role-based
# Regular cleanup
# Use private registry
# Harbor, Nexus

Q994: How do you implement secure networking?

Section titled “Q994: How do you implement secure networking?”

Answer:

# Default deny all
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress

Answer:

Terminal window
# Use RBAC
# Enable TLS
# Use strong auth
# Don't expose publicly
# Use VPN
# Enable audit logging
# Monitor access
# Use admission controllers

Answer:

Terminal window
# Multiple layers
# Network, host, container
# Monitoring
# Real-time alerts
# Quick response
# Automated blocking
# Regular testing
# Pen testing
# Updates
# Patch quickly

Answer:

# Pod Security Standards
# Restricted profile
# Use security contexts
securityContext:
runAsNonRoot: true
readOnlyRootFilesystem: true
# Use NetworkPolicies
# Use Secrets
# External secrets

Answer:

Terminal window
# Use policy engines
# OPA, Kyverno
# Use scanning tools
# OpenSCAP, Kube-bench
# Use audit logging
# Regular reviews
# Automate checks
# In CI/CD pipeline

Answer:

Terminal window
# Use RBAC
# Network policies
# Encrypt etcd
# Enable audit logging
# Update regularly
# Use CIS benchmarks
# Monitor
# Use Falco
# Use secrets management

Answer:

Terminal window
# Verify everything
# Never trust, always verify
# mTLS everywhere
# Short-lived certificates
# Network policies
# Microsegmentation
# Identity-based
# Not IP-based
# Continuous verification
# This concludes the 1000 Linux practical interview questions!

End of Linux Practical Interview Questions (1-1000)