Get all pods across namespaces
Lists all pods across all namespaces in the cluster.
kubectl get pods --all-namespaces
Commands I reach for across Kubernetes, AWS, GCP, Terraform, Linux and the tools around them, plus short playbooks for common incidents. Fill in a placeholder once and every command uses it.
Lists all pods across all namespaces in the cluster.
kubectl get pods --all-namespaces
Get recent events in a namespace sorted by their creation time.
kubectl get events --sort-by='.metadata.creationTimestamp'
Displays CPU and Memory usage for all nodes.
kubectl top nodes
Bypasses graceful termination to kill a pod.
Caution. Removes the pod from the API without waiting for the kubelet to confirm it stopped. A StatefulSet pod can end up running twice against the same volume. Try a normal delete first.
kubectl delete pod <pod-name> --grace-period=0 --force
Forwards local port to a service port.
kubectl port-forward svc/<service-name> 8080:80
Fetches and decodes a base64 Kubernetes secret.
kubectl get secret <secret-name> -o jsonpath='{.data.<key>}' | base64 --decode
Prints the secret in plain text to your terminal and its scrollback.
Useful for checking why a pod crashed before it restarted.
kubectl logs <pod-name> --previous
Check if your current user has permission to perform an action.
kubectl auth can-i create deployments --namespace dev
Generates the YAML for a resource without actually creating it.
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx.yaml
Cordons the node and evicts its pods before maintenance, respecting PodDisruptionBudgets.
Caution. --delete-emptydir-data deletes the data in emptyDir volumes on that node.
kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data
Opens an interactive shell session inside a running pod.
kubectl exec -it <pod-name> -- /bin/sh
Triggers a rolling restart of all pods in a deployment.
kubectl rollout restart deployment/<deployment-name>
Sets the replica count of a deployment.
kubectl scale deployment/<deployment-name> --replicas=5
If a HorizontalPodAutoscaler manages the deployment, it will change the count back.
Updates the container image of a deployment without editing YAML.
kubectl set image deployment/<deployment-name> <container-name>=<image-name>:<tag>
Shows the documentation and fields for a specific Kubernetes resource.
kubectl explain pod.spec.containers
Checks the revision history of a deployment.
kubectl rollout history deployment/<deployment-name>
Exports the live YAML configuration of a running pod.
kubectl get pod <pod-name> -o yaml
Updates a field on a resource without an editor.
kubectl patch deployment <deployment-name> -p '{"spec": {"replicas": 3}}'
Adds or updates a label on a Kubernetes node for scheduling.
kubectl label node <node-name> env=production
Adds a taint to a node to repel pods that don't tolerate it.
kubectl taint nodes <node-name> key=value:NoSchedule
Creates a ConfigMap from a local file.
kubectl create configmap my-config --from-file=config.properties
Rolls back a deployment to the previous revision.
kubectl rollout undo deployment/<deployment-name>
Shows all available contexts in your kubeconfig.
kubectl config get-contexts
Changes the active Kubernetes context.
kubectl config use-context <context-name>
Shows CPU and memory usage of pods sorted by CPU.
kubectl top pods --sort-by=cpu --all-namespaces
Lists pods where a container last terminated with OOMKilled.
kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"/"}{.metadata.name}{" "}{.status.containerStatuses[*].lastState.terminated.reason}{"\n"}{end}' | grep OOMKilled
Shows a pod's status, container states, restart reasons and recent events.
kubectl describe pod <pod-name> -n <namespace>
Waits for a deployment rollout and exits non-zero if it fails.
kubectl rollout status deployment/<deployment-name> -n <namespace>
Marks a node unschedulable; running pods stay where they are.
kubectl cordon <node-name>
Lists all Helm deployments in the cluster.
helm ls --all-namespaces
Rolls back a Helm deployment to a specific prior revision.
helm rollback <release-name> <revision-number>
Fetches the values.yaml that was actually applied to a deployed release.
helm get values <release-name>
Installs a helm chart, or upgrades it if it already exists.
helm upgrade --install <release-name> <chart-path>
Renders the chart templates locally without applying them to the cluster.
helm template <release-name> <chart-path>
Adds a chart repository to Helm's local repo list.
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts && helm repo update
Prints the default values.yaml of a chart before installing.
helm show values <chart-name>
Shows the revision history and status of a Helm release.
helm history <release-name>
Removes all resources associated with a Helm release.
Caution. Deletes every resource in the release. Add --keep-history to keep the release record for a later rollback.
helm uninstall <release-name> --namespace <namespace>
Validates a chart for possible issues before deploying.
helm lint ./my-chart
Prints the rendered Kubernetes manifests Helm applied for a release.
helm get manifest <release-name> -n <namespace>
Upgrades a release, waits for it to become ready and rolls back automatically if it doesn't.
helm upgrade --install <release-name> <chart-path> -n <namespace> --atomic --wait --timeout 5m
Helm 4 renamed --atomic to --rollback-on-failure.
Pulls a chart version and unpacks it locally so you can read its templates and values.
helm pull <helm-repo>/<chart> --version <version> --untar
Shows what an upgrade would change in the cluster before you run it.
helm diff upgrade <release-name> <chart-path> -n <namespace>
Needs the helm-diff plugin: helm plugin install https://github.com/databus23/helm-diff
Tails the logs of the Karpenter controller pod.
kubectl logs -f -n kube-system -l app.kubernetes.io/name=karpenter
Current install guides use kube-system; older installs used a karpenter namespace.
Shows all NodeClaims provisioned by Karpenter.
kubectl get nodeclaims
Filters Karpenter logs specifically for scale-down and disruption events.
kubectl logs -n kube-system -l app.kubernetes.io/name=karpenter | grep -i disrupt
Shows all Karpenter NodePool configurations.
kubectl get nodepools
Shows detailed info about a specific NodeClaim including instance type.
kubectl describe nodeclaim <nodeclaim-name>
Shows all EC2NodeClass resources used by Karpenter for AWS configuration.
kubectl get ec2nodeclasses
Shows each NodePool's CPU limit next to the CPU it has provisioned.
kubectl get nodepools -o custom-columns=NAME:.metadata.name,CPU_LIMIT:.spec.limits.cpu,CPU_USED:.status.resources.cpu
Streams NodeClaim changes as Karpenter provisions and consolidates nodes.
kubectl get nodeclaims -w
Shows a pod's scheduling events, where Karpenter reports why no NodePool fits it.
kubectl get events -n <namespace> --field-selector involvedObject.name=<pod-name> --sort-by=.lastTimestamp
Stops Karpenter from consolidating, expiring or replacing the node this pod runs on.
kubectl annotate pod <pod-name> -n <namespace> karpenter.sh/do-not-disrupt=true
Remove it with the same command and a trailing minus: karpenter.sh/do-not-disrupt-
Prints the consolidation policy and disruption budgets of a NodePool.
kubectl get nodepool <nodepool-name> -o jsonpath='{.spec.disruption}'
Uploads a local directory to an S3 bucket.
aws s3 sync ./my-folder s3://<bucket>
Add --delete to also remove objects that no longer exist locally. Try --dryrun first.
Recursively deletes all objects in an S3 bucket.
Caution. Permanently deletes every object. Run it with --dryrun first. On a versioned bucket it only adds delete markers; the old versions stay and still cost money.
aws s3 rm s3://<bucket> --recursive
Returns the ID, Type, and State of running EC2s.
aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" --query "Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name]" --output table
Verifies which AWS IAM user/role you are currently authenticated as.
aws sts get-caller-identity
Generates or updates kubeconfig for EKS.
aws eks update-kubeconfig --region <region> --name <cluster-name>
Authenticates via AWS IAM Identity Center (SSO).
aws sso login --profile <profile-name>
Gets a token and pipes it to docker login for AWS ECR.
aws ecr get-login-password --region <region> | docker login --username AWS --password-stdin <account_id>.dkr.ecr.<region>.amazonaws.com
Checks if actual resources have deviated from the CFN template.
aws cloudformation detect-stack-drift --stack-name <stack-name>
Returns a detection ID. Check the result with aws cloudformation describe-stack-drift-detection-status --stack-drift-detection-id <id>.
Creates a temporary URL (valid for 1 hour) to securely share an S3 object.
aws s3 presign s3://<bucket>/<key> --expires-in 3600
Anyone with the URL can download the object until it expires.
Streams real-time logs from an AWS CloudWatch Log Group.
aws logs tail /aws/lambda/<function-name> --follow
Fetches the plain text value of a secret from AWS Secrets Manager.
aws secretsmanager get-secret-value --secret-id <secret-name> --query SecretString --output text
Prints the secret in plain text to your terminal.
Lists all access keys for a user to identify old keys needing rotation.
aws iam list-access-keys --user-name <username>
Copies a single local file to an S3 bucket.
aws s3 cp local-file.txt s3://<bucket>/
Synchronously invokes a Lambda function from the CLI.
aws lambda invoke --function-name <function-name> --cli-binary-format raw-in-base64-out --payload '{}' response.json
AWS CLI v2 expects base64 payloads unless you pass --cli-binary-format raw-in-base64-out.
Gets a list of all RDS database instances.
aws rds describe-db-instances --query 'DBInstances[*].[DBInstanceIdentifier,DBInstanceStatus]' --output table
Stops a running EC2 instance by instance ID.
aws ec2 stop-instances --instance-ids <instance-id>
Data on instance store volumes is lost when the instance stops.
Starts a stopped EC2 instance.
aws ec2 start-instances --instance-ids <instance-id>
Lists all DNS hosted zones in Route53.
aws route53 list-hosted-zones --output table
Lists all Application and Network Load Balancers.
aws elbv2 describe-load-balancers --query 'LoadBalancers[*].[LoadBalancerName,State.Code,DNSName]' --output table
Opens a shell session to an EC2 instance via Systems Manager (no SSH key needed).
aws ssm start-session --target <instance-id>
Needs the Session Manager plugin for the AWS CLI and the SSM agent on the instance.
Fetches cost and usage data grouped by service for the current month.
aws ce get-cost-and-usage --time-period Start=$(date +%Y-%m-01),End=$(date -d tomorrow +%Y-%m-%d) --granularity MONTHLY --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE
Each Cost Explorer API request costs $0.01. Uses GNU date; on macOS use gdate.
Lists all images in an ECR repository sorted by push date.
aws ecr describe-images --repository-name <repo-name> --query 'sort_by(imageDetails,& imagePushedAt)[*].[imageTags[0],imagePushedAt]' --output table
Sends a test message to an SQS queue.
aws sqs send-message --queue-url <queue-url> --message-body '{"test": "hello"}'
Reads the first 10 items of a DynamoDB table.
aws dynamodb scan --table-name <table-name> --max-items 10
A scan reads the table page by page and consumes read capacity; avoid full scans on large tables.
Shows every CloudWatch alarm currently in the ALARM state.
aws cloudwatch describe-alarms --state-value ALARM --output table
Authorizes the gcloud CLI to access Google Cloud Platform with your user credentials.
gcloud auth login
Sets the default project ID for all subsequent gcloud commands.
gcloud config set project <project-id>
Fetches cluster credentials for Google Kubernetes Engine and updates your local kubeconfig.
gcloud container clusters get-credentials <cluster-name> --region <region>
Lists all Google Compute Engine instances in the active project.
gcloud compute instances list
Securely connects to a Compute Engine virtual machine via Identity-Aware Proxy (IAP).
gcloud compute ssh <instance-name> --zone <zone> --tunnel-through-iap
Fetches the complete IAM policy (roles and members) bound to the current project.
gcloud projects get-iam-policy <project-id>
Synchronizes the contents of a local directory to a Google Cloud Storage bucket.
gcloud storage rsync ./my-folder gs://<bucket> --recursive
gcloud storage replaces gsutil, which Google now treats as legacy.
Shows the total size of a Cloud Storage bucket.
gcloud storage du gs://<bucket> --summarize --readable-sizes
Executes a standard SQL query directly against BigQuery from the command line.
bq query --use_legacy_sql=false 'SELECT * FROM `project.dataset.table` LIMIT 10'
Deploys a container image to Cloud Run as a fully managed serverless service.
gcloud run deploy <service-name> --image <image> --region <region>
Add --allow-unauthenticated only if the service should be public on the internet.
Retrieves the decoded payload of a secret stored in GCP Secret Manager.
gcloud secrets versions access latest --secret="<secret-name>"
Prints the secret in plain text to your terminal.
Publishes a test message to a Cloud Pub/Sub topic.
gcloud pubsub topics publish <topic-name> --message="Hello World"
Lists all VPC networks and their subnet modes in the project.
gcloud compute networks list
Authenticates your local environment so code can use GCP APIs natively.
gcloud auth application-default login
Lists all deployed Cloud Run services in the active project.
gcloud run services list
Connects with the mysql or psql client, allowlisting your IP address for a few minutes.
gcloud sql connect <instance-name> --user=<user>
Shows all firewall rules in the project.
gcloud compute firewall-rules list
Fetches the last 20 log entries from Cloud Logging.
gcloud logging read "resource.type=gce_instance" --limit 20 --format json
Lists container image repositories in Artifact Registry.
gcloud artifacts repositories list --location=<region>
Deploys a Python Cloud Function triggered by HTTP.
gcloud functions deploy <function-name> --gen2 --region=<region> --runtime=python312 --source=. --entry-point=main --trigger-http
Add --allow-unauthenticated only if the function should be public on the internet.
Lists all service accounts in the project.
gcloud iam service-accounts list
Lists all persistent disks in the project.
gcloud compute disks list
Lists all managed DNS zones in the project.
gcloud dns managed-zones list
Lists node pools for a specific GKE cluster.
gcloud container node-pools list --cluster=<cluster-name> --region=<region>
Lists billing accounts you have access to.
gcloud billing accounts list
Generates an execution plan to a file.
terraform plan -out=tfplan
Applies changes automatically.
Caution. Applies without showing a plan for approval. Use it only in CI, ideally on a reviewed saved plan: terraform apply tfplan.
terraform apply -auto-approve
Brings existing cloud resource under TF state.
terraform import <resource_address> <cloud-resource-id>
Terraform 1.5 and later also support import blocks in configuration, which show up in the plan.
Removes a resource from state tracking without destroying the actual cloud resource.
terraform state rm <resource_address>
Terraform stops managing the resource; it keeps running. Back up the state first.
Manually removes a lock on the state file if a previous pipeline crashed.
Caution. Only when you are sure no other run holds the lock. Two runs writing the same state can corrupt it.
terraform force-unlock <lock-id>
Initializes terraform and upgrades all providers to their latest allowed versions.
terraform init -upgrade
Shows all available state workspaces.
terraform workspace list
Validates the syntax and internal consistency of terraform files.
terraform validate
Rewrites all .tf files to a canonical format.
terraform fmt -recursive
Displays the output values from your terraform state.
terraform output -json
Shows all resources currently tracked by terraform.
terraform state list
Displays attributes of a single resource in the state.
terraform state show <resource_address>
Generates a visual dependency graph of resources in DOT format.
terraform graph | dot -Tpng > graph.png
Needs Graphviz for the dot command.
Plans the destroy and re-create of one resource. Replaces the deprecated terraform taint.
terraform apply -replace=<resource_address>
Creates and switches to a new terraform workspace.
terraform workspace new <workspace-name>
Stops running containers, then removes stopped containers, unused images, networks, build cache and volumes.
Caution. Destructive: deletes every unused volume, database data included. Leave out --volumes to keep volumes.
docker ps -q | xargs -r docker stop && docker system prune -a --volumes -f
Starts an interactive shell inside a running container.
docker exec -it <container-id> /bin/sh
Use /bin/bash if the image has it.
Shows a live stream of CPU/Memory usage.
docker stats
Forces a completely fresh docker build bypassing all cached layers.
docker build --no-cache -t <image-name>:<tag> .
Removes dangling images: untagged <none> layers left behind by rebuilds.
docker image prune -f
Starts all services defined in a docker-compose.yml in the background.
docker compose up -d
Extracts the internal IP address of a running docker container.
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container-id>
Tails the logs of a docker container continuously.
docker logs -f <container-id>
Lists all Docker volumes on the host.
docker volume ls
Lists all Docker networks.
docker network ls
Tags a local image with a new name for pushing to a registry.
docker tag <image-id> <registry>/<repo>:<tag>
Pushes a tagged image to a container registry.
docker push <registry>/<repo>:<tag>
Copies a file from inside a running container to the host.
docker cp <container-id>:/path/in/container /local/path
Shows the build history and layer sizes of a Docker image.
docker history <image-name>
Writes an image to a tar file for offline transfer. Load it on the other host with docker load -i image.tar.
docker save -o image.tar <image-name>:<tag>
Undoes the last commit and keeps its changes in the working directory.
git reset HEAD~1
If the commit is already pushed, use git revert instead.
Discards local changes to match remote.
Caution. Destroys uncommitted changes and local commits that are not on the remote. Stash or branch first if in doubt.
git fetch --all && git reset --hard origin/<branch-name>
Deletes branches already merged into main.
git branch --merged main | grep -Ev '^\*|^[[:space:]]*(main|master)$' | xargs -r git branch -d
Interactively choose which changes to stash.
git stash push -p -m "message"
Starts an interactive rebase for the last N commits.
git rebase -i HEAD~3
Applies the changes introduced by a specific commit from another branch.
git cherry-pick <commit-hash>
Fetches updates and removes local tracking branches that were deleted on remote.
git fetch -p
Fetches and immediately rebases your current branch onto the latest origin/main.
git pull --rebase origin main
Creates a version tag with a message.
git tag -a v1.0.0 -m 'Release v1.0.0'
Uses binary search to find the commit that introduced a bug.
git bisect start && git bisect bad && git bisect good <known-good-commit>
Shows a compact, colorful branch/merge history.
git log --oneline --graph --decorate --all
Shows the diff of files staged for the next commit.
git diff --staged
Shows who last modified each line of a file.
git blame <filename>
Lists the most recent GitHub Actions workflow runs (requires gh cli).
gh run list --limit 5
Follows the logs of a running GitHub Actions workflow.
gh run watch
Uses nektos/act to run your github actions locally via docker.
act -l
Creates a pull request from the current branch using GitHub CLI.
gh pr create --title "feat: my feature" --body "Description" --base main
Merges a pull request using squash merge.
gh pr merge --squash --delete-branch
Creates a new release on GitHub with auto-generated notes.
gh release create v1.0.0 --generate-notes
Triggers a Jenkins job build remotely using curl.
curl -X POST "https://jenkins.example.com/job/<job-name>/build" --user "<user>:$JENKINS_TOKEN"
Reads the API token from an environment variable so it stays out of your shell history.
Scans a container image for known CVEs.
docker scout cves <image-name>:<tag>
Scans a container image for vulnerabilities using Trivy.
trivy image <image-name>:<tag>
Lints a Dockerfile for best practices and common mistakes.
hadolint Dockerfile
Forces a sync of an ArgoCD application.
argocd app sync <app-name>
Shows the diff between the live state and desired state in ArgoCD.
argocd app diff <app-name>
Triggers a workflow_dispatch event on a GitHub Actions workflow.
gh workflow run <workflow-name>
Bumps the version in package.json using npm.
npm version patch -m 'chore: bump version to %s'
Re-runs only the jobs that failed in a GitHub Actions run.
gh run rerun <run-id> --failed
Prints the logs of only the failed steps of a GitHub Actions run.
gh run view <run-id> --log-failed
Checks the workflow files in .github/workflows for syntax and expression errors.
actionlint
Verifies connectivity and python availability on all inventory hosts.
ansible all -m ping -i inventory.ini
Runs a playbook in check mode to see what would change without actually changing anything.
ansible-playbook playbook.yml --check --diff
Collects system information (facts) from a specific host.
ansible <hostname> -m setup
Executes a one-off shell command on all hosts.
ansible all -m shell -a 'uptime' -i inventory.ini
Encrypts a sensitive file (like secrets.yml) using Ansible Vault.
ansible-vault encrypt secrets.yml
Decrypts and displays the contents of a vault-encrypted file.
ansible-vault view secrets.yml
Displays the host/group structure of your inventory as a tree.
ansible-inventory --graph -i inventory.ini
Runs only the tasks tagged with a specific tag.
ansible-playbook playbook.yml --tags deploy
Installs a collection of modules and plugins from Ansible Galaxy.
ansible-galaxy collection install community.general
Checks playbooks for best practices and potential issues.
ansible-lint playbook.yml
Runs a playbook only on the hosts or groups you name.
ansible-playbook playbook.yml -i inventory.ini --limit <host>
Starts a playbook at the named task and asks before running each one.
ansible-playbook playbook.yml -i inventory.ini --start-at-task "<task-name>" --step
Reads a value from stdin (finish with Ctrl+D) and prints an encrypted variable to paste into a vars file.
ansible-vault encrypt_string --stdin-name '<variable-name>'
Lists the 10 largest files and directories here (dotfiles excluded).
du -hs * | sort -rh | head -10
Finds files over 100 MB on the root filesystem, largest first.
sudo find / -xdev -type f -size +100M -exec du -h {} + 2>/dev/null | sort -rh | head -20
Follows journalctl logs for a service in real-time.
journalctl -u <service-name> -f
Sends SIGTERM to the process listening on a TCP port.
Caution. Use kill -9 only if the process ignores SIGTERM: -9 skips its shutdown and cleanup.
kill $(lsof -t -i:<port> -sTCP:LISTEN)
Lists the top 10 processes consuming the most CPU.
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -11
Searches for a string inside all files in a directory.
grep -rnw '/path/to/somewhere/' -e 'pattern'
Creates a symbolic link pointing to a target file or directory.
ln -s /path/to/target /path/to/link
Recursively changes permissions of directories only (leaving files untouched).
find . -type d -exec chmod 755 {} \;
Prints only the 3rd and 5th columns of a space-separated file.
awk '{print $3, $5}' data.txt
Replaces 'old-string' with 'new-string' inline in a file.
sed -i 's/old-string/new-string/g' config.yaml
GNU sed. On macOS, use sed -i '' instead of sed -i.
Finds .log files older than 30 days under /var/log and deletes them.
Caution. Deletes files permanently. Run it once without -delete to see the list first.
sudo find /var/log -type f -name "*.log" -mtime +30 -delete
Uses rsync to synchronize two directories over SSH, showing progress.
rsync -avz --progress /local/dir/ user@remote:/remote/dir/
Shows total, used and available memory in human-readable units.
free -h
Shows filesystem disk space usage and types.
df -Th
Finds files owned by root and changes them to another user.
Caution. Changes ownership of everything it matches. Check the path first; run against / it can break the system.
find /path -user root -exec chown user:group {} +
Compresses a directory into a tarball.
tar -czvf archive.tar.gz /path/to/dir
Runs a command repeatedly every 2 seconds, refreshing output.
watch -n 2 'kubectl get pods'
Shows TCP and UDP sockets in the LISTEN state with the owning process. The modern replacement for netstat -tulnp.
sudo ss -tulpn
Shows all block devices (disks, partitions) in a tree view.
lsblk -f
Enables a systemd service to start automatically on boot.
sudo systemctl enable <service-name>
Searches your bash history for a specific command.
history | grep <keyword>
Opens the crontab editor to schedule recurring tasks.
crontab -e
Creates a new system user with a home directory.
sudo useradd -m -s /bin/bash <username>
Shows how long the system has been running plus load averages.
uptime
Shows kernel ring buffer messages, useful for hardware/driver debugging.
sudo dmesg --level=err,warn -T | tail -30
Extracts a compressed tarball archive to the current directory.
tar -xzvf archive.tar.gz
Fetches only the HTTP response headers.
curl -I https://example.com
Follows the DNS delegation path from root servers.
dig +trace <domain>
Uses netcat to check if a remote TCP port is reachable.
nc -vz <hostname> <port>
Captures and displays raw network traffic on a specific port.
sudo tcpdump -i any port 80 -n -v
Fetches and displays the expiration date of a remote SSL certificate.
echo | openssl s_client -servername example.com -connect example.com:443 2>/dev/null | openssl x509 -noout -dates
Fetches a JSON API response and formats it nicely using jq.
curl -s https://api.github.com/users/octocat | jq '.'
Tests the Nginx config files for syntax errors before reloading.
sudo nginx -t
Reloads the Nginx configuration without dropping active connections.
sudo nginx -s reload
Tails the Nginx access logs and uses awk to show only IPs and HTTP status.
tail -f /var/log/nginx/access.log | awk '{print $1, $9}'
Determines exactly which interface and route will be used to reach an IP.
ip route get 8.8.8.8
Forces ping to use a specific network interface.
ping -I eth1 8.8.8.8
Combines ping and traceroute for real-time network path analysis.
mtr --report <hostname>
Shows all current iptables firewall rules with line numbers.
sudo iptables -L -n -v --line-numbers
Queries a DNS server to resolve a domain name.
nslookup <domain> 8.8.8.8
Downloads an entire website for offline browsing.
wget --mirror --convert-links --page-requisites <url>
Sends a JSON payload to an API endpoint.
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' https://api.example.com/endpoint
Fetches domain registration information.
whois example.com
Tunnels local port 8080 securely to remote port 80 via a bastion host.
ssh -L 8080:localhost:80 [email protected]
Generates a highly secure modern SSH key pair.
ssh-keygen -t ed25519 -C "[email protected]"
Creates a new 2048-bit RSA private key and a Certificate Signing Request.
openssl req -new -newkey rsa:2048 -nodes -keyout mydomain.key -out mydomain.csr
The private key is written unencrypted (-nodes); keep mydomain.key private.
Reads an x509 certificate file and outputs its details.
openssl x509 -in certificate.crt -text -noout
Performs a fast network scan to find open ports on a target IP.
Caution. Scan only hosts and networks you own or have written permission to test.
nmap -F 192.168.1.1
Secures a private SSH key file so only the owner can read it.
chmod 600 ~/.ssh/id_ed25519
Shows the status of fail2ban jails and banned IPs.
sudo fail2ban-client status sshd
Encrypts a file using symmetric encryption with GPG.
gpg -c sensitive-file.txt
Finds all binaries with the SUID bit set (potential privilege escalation vectors).
find / -perm -4000 -type f 2>/dev/null
Displays the last 20 user login records.
last -n 20
Prompts for a password and prints its bcrypt hash, so the password never lands in your shell history.
python3 -c "import bcrypt, getpass; print(bcrypt.hashpw(getpass.getpass().encode(), bcrypt.gensalt()).decode())"
Needs the bcrypt package: pip install bcrypt.
Installs your public key on a remote server for passwordless login.
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@remote-host
Checks Terraform, Kubernetes manifests and Dockerfiles in the current directory against security rules.
trivy config .
Searches the git history of the current repository for keys, tokens and passwords.
gitleaks git -v .
Versions before 8.19 use gitleaks detect instead.
Generates and saves a CSV of every IAM user with password, access key and MFA status.
aws iam generate-credential-report && aws iam get-credential-report --query Content --output text | base64 --decode > credential-report.csv
If the report is not ready yet, wait a few seconds and run the second command again.
Shows every action a Kubernetes service account is allowed to perform in a namespace.
kubectl auth can-i --list -n <namespace> --as=system:serviceaccount:<namespace>:<service-account>
Needs permission to impersonate service accounts.
Creates a logical backup of a PostgreSQL database.
pg_dump -U <username> -h <host> -d <database_name> > backup.sql
Add -Fc for a compressed custom-format dump that pg_restore can restore selectively.
Imports an SQL file into a MySQL database.
Caution. Dumps made by mysqldump include DROP TABLE statements by default, so existing tables are replaced.
mysql -u <username> -p <database_name> < backup.sql
Connects to redis-cli and deletes all keys in all databases.
Caution. Deletes every key in every database on the server. There is no undo.
redis-cli flushall
Restores a dump made with pg_dump -Fc, in a single transaction.
pg_restore -U <username> -h <host> -d <database_name> -1 backup.dump
pg_restore can't read a plain .sql dump; restore that with psql -d <database_name> -f backup.sql.
Dumps a MySQL database to an SQL file; --single-transaction gives a consistent InnoDB dump without locking tables.
mysqldump -u <username> -p --single-transaction <database_name> > backup.sql
Shows detailed information about the Redis server.
redis-cli info
Lists keys matching a glob-style pattern without blocking the server.
redis-cli --scan --pattern 'user:*'
Avoid KEYS in production: it blocks Redis while it walks every key.
Exports a MongoDB collection to a JSON file.
mongoexport --db=mydb --collection=users --out=users.json
Imports a JSON file into a MongoDB collection.
mongoimport --db=mydb --collection=users --file=users.json
Shows all active connections and their states in PostgreSQL.
psql -c "SELECT pid, usename, state, query FROM pg_stat_activity WHERE state != 'idle';"
Shows the size of each database in PostgreSQL.
psql -c "SELECT pg_database.datname, pg_size_pretty(pg_database_size(pg_database.datname)) FROM pg_database;"
Shows all currently running queries in MySQL.
mysql -e 'SHOW FULL PROCESSLIST;'
Lists sessions waiting on a lock and the PIDs blocking them.
psql -c "SELECT pid, pg_blocking_pids(pid) AS blocked_by, state, wait_event_type, left(query, 60) AS query FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;"
Terminates a backend by PID, for example the one blocking others.
Caution. Ends the session and rolls back its open transaction. Try pg_cancel_backend(<backend-pid>) first, which cancels only the running query.
psql -c "SELECT pg_terminate_backend(<backend-pid>);"
Samples the keyspace with SCAN and reports the biggest key of each type.
redis-cli --bigkeys
Uses SCAN, so it doesn't block the server, but it adds load; run it off-peak.
Fetches the current health status of the ES cluster.
curl -X GET "localhost:9200/_cluster/health?pretty"
Shows all indices in the ES cluster with their health, status, and size.
curl -X GET "localhost:9200/_cat/indices?v"
Deletes one index.
Caution. Permanently deletes the index and its data.
curl -X DELETE "localhost:9200/<index-name>"
CPU cores used per pod, averaged over 5 minutes. container!="" drops the pod-level series that would double-count.
sum by (pod) (rate(container_cpu_usage_seconds_total{namespace="<namespace>", container!=""}[5m]))
Working-set memory per pod in MiB: the figure kubectl top shows and the kubelet uses for eviction.
sum by (pod) (container_memory_working_set_bytes{namespace="<namespace>", container!=""}) / 1024 / 1024
Restarts the grafana systemd service.
sudo systemctl restart grafana-server
Fetches current metric values from the Prometheus HTTP API.
curl -s "http://localhost:9090/api/v1/query?query=up" | jq .
Lists all scrape targets and their health status.
curl -s "http://localhost:9090/api/v1/targets" | jq '.data.activeTargets[] | {job: .labels.job, health: .health}'
Lists all configured data sources in Grafana via API.
curl -s -H "Authorization: Bearer <service-account-token>" http://localhost:3000/api/datasources | jq .
Grafana service account tokens replace the old API keys.
Shows the current status and active alerts in Alertmanager.
curl -s http://localhost:9093/api/v2/alerts | jq .
Fetches raw metrics from Node Exporter.
curl -s http://localhost:9100/metrics | grep node_cpu_seconds_total | head -5
Queries Loki for logs matching a label selector.
curl -G -s "http://localhost:3100/loki/api/v1/query_range" --data-urlencode 'query={job="varlogs"}' | jq .
Calculates the percentage of 5xx responses over the last 5 minutes.
sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) * 100
Calculates the 99th percentile request latency from a histogram.
histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))
Verifies that the Kubernetes metrics-server is running and healthy.
kubectl get deployment metrics-server -n kube-system
Tests HTTP endpoint availability using Blackbox Exporter.
curl -s "http://localhost:9115/probe?target=https://example.com&module=http_2xx" | grep probe_success
Fetches recent traces from Jaeger for a specific service.
curl -s "http://localhost:16686/api/traces?service=my-service&limit=5" | jq '.data[].traceID'
Fetches container-level resource stats from cAdvisor.
curl -s http://localhost:8080/api/v1.3/containers | jq '.spec.cpu'
Validates the syntax of alerting and recording rules before you load them.
promtool check rules rules.yml
Validates alertmanager.yml and summarises its receivers and routes.
amtool check-config alertmanager.yml
Silences an alert by name for two hours, with a comment saying why.
amtool silence add alertname="<alert-name>" --duration=2h --comment="<reason>" --alertmanager.url=http://localhost:9093
Tells Prometheus to re-read its configuration and rule files without a restart.
curl -X POST http://localhost:9090/-/reload
Works only when Prometheus runs with --web.enable-lifecycle.
Prints out all system calls a PID makes (crucial for deep debugging).
strace -p <pid>
Slows the traced process noticeably; be careful on busy production hosts.
Shows all files, sockets, and connections opened by a PID.
lsof -p <pid>
Shows a live view of the hottest CPU functions in the system.
sudo perf top
Shows system performance statistics (CPU, memory, I/O) every 2 seconds.
vmstat 2 10
Shows CPU and disk I/O stats, refreshing every second.
iostat -xz 1
Groups and counts TCP connections by their state (ESTABLISHED, TIME_WAIT, etc.).
ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c | sort -rn
Writes a core file and lets the process carry on; it pauses only while the dump is written. gcore ships with gdb.
sudo gcore -o core <pid>
Shows detailed timing of DNS, connect, TLS, and transfer phases.
curl -o /dev/null -s -w "DNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTLS: %{time_appconnect}s\nTotal: %{time_total}s\n" https://example.com
Attaches a temporary debug container that shares the target container's processes; useful when the image has no shell.
kubectl debug -it <pod-name> -n <namespace> --image=busybox:1.36 --target=<container-name>
Lists files that were deleted but are still open. Their space is not freed until the process closes them, so a disk can be full while du looks fine.
sudo lsof +L1
Searches the kernel log for processes the OOM killer ended.
sudo journalctl -k | grep -iE 'out of memory|killed process'