DevOps

DevOps Tools: Docker, Jenkins, and Git Cheat Sheet

Introduction

In the world of DevOps, efficiency and automation are the keys to success. Whether you’re managing containers with Docker, orchestrating them with Kubernetes, automating builds with Jenkins, or keeping track of your code with Git, each tool plays a critical role in streamlining your workflow. However, these tools can be complex, with a myriad of commands and configurations to remember. That’s where a cheat sheet comes in handy!

This guide is designed to give you a quick reference to the most essential commands and best practices for Docker, Kubernetes, Jenkins, and Git. Whether you’re a beginner looking to get started or a seasoned pro needing a refresher, this cheat sheet has something for everyone. Let’s dive in and make your DevOps journey smoother and more efficient!

Docker Cheat Sheet

Here’s a quick reference to help you navigate Docker’s core features and commands.

Installation and Setup

PlatformInfoCommand
GeneralInstall Docker Engine on your system.Follow Docker’s Installation Guide.
LinuxInstall Docker using the package manager.sudo apt-get install docker-ce
macOSInstall Docker Desktop.brew install –cask docker
WindowsInstall Docker Desktop.Docker Desktop for Windows
Installation And Setup

Docker Images: Pull, Build, and List Commands

TaskCommandDescription
Pull an Imagedocker pull <image_name>Downloads a Docker image from Docker Hub.
Pull a Specific Versiondocker pull <image_name>:<tag>Downloads a specific version of an image (e.g., nginx:alpine).
Build an Imagedocker build -t <image_name> .Builds an image from a Dockerfile in the current directory.
Tag an Imagedocker tag <image_id> <repository>:<tag>Tags an existing image with a new repository and tag.
List Imagesdocker imagesDisplays all Docker images stored locally.
Remove an Imagedocker rmi <image_id>Deletes a specific image from local storage.
Inspect an Imagedocker inspect <image_name>Displays detailed information about an image.
Docker Images

Containers: Create, Start, Stop, and Remove

TaskCommandDescription
Create and Start a Containerdocker run -d –name <container_name> <image_name>Creates and starts a container in detached mode.
Run a Container with Portsdocker run -d -p <host_port>:<container_port> <image_name>Runs a container with specific port mapping.
Run a Container with Environment Variablesdocker run -d -e <env_var>=<value> <image_name>Runs a container with environment variables.
Start an Existing Containerdocker start <container_name>Starts a previously stopped container.
Stop a Running Containerdocker stop <container_name>Gracefully stops a running container.
Restart a Containerdocker restart <container_name>Restarts a container.
Remove a Containerdocker rm <container_name>Removes a stopped container.
View Running Containersdocker psLists all currently running containers.
View All Containersdocker ps -aLists all containers, including stopped ones.
Inspect a Containerdocker inspect <container_name>Displays detailed information about a container.
View Container Logsdocker logs <container_name>Displays logs generated by a container.
Containers

Docker Networking Basics: Creating and Managing Networks

TaskCommandDescription
Create a Networkdocker network create <network_name>Creates a new Docker network for containers.
List Networksdocker network lsLists all Docker networks.
Inspect a Networkdocker network inspect <network_name>Displays detailed information about a specific network.
Connect a Container to a Networkdocker network connect <network_name> <container_name>Connects a running container to the specified network.
Disconnect a Container from a Networkdocker network disconnect <network_name> <container_name>Disconnects a container from the specified network.
Remove a Networkdocker network rm <network_name>Deletes a Docker network.
Run Container on Specific Networkdocker run –network <network_name> <image_name>Starts a container attached to a specific network.
Create Network with Subnetdocker network create –subnet=<subnet> <network_name>Creates a network with a specified subnet (e.g., –subnet=192.168.1.0/24).
Docker Networking

Advanced Docker Commands

Docker Compose: Setting Up Multi-Container Environments

TaskCommandDescription
Install Docker Composesudo apt-get install docker-composeInstalls Docker Compose on your system.
Create a Docker Compose Filetouch docker-compose.ymlCreates a docker-compose.yml file to define multi-container setups.
Start Services Defined in Docker Composedocker-compose upStarts all services defined in the docker-compose.yml file.
Start in Detached Modedocker-compose up -dStarts services in the background (detached mode).
Stop Servicesdocker-compose downStops all running services and removes the containers.
List Running Servicesdocker-compose psLists all running services managed by Docker Compose.
View Logs for All Servicesdocker-compose logsDisplays combined logs from all services.
Scale Servicesdocker-compose up –scale <service_name>=<number>Scales a service to the specified number of instances.
Rebuild Servicesdocker-compose up –buildRebuilds the images for all services before starting.
Remove Stopped Containers and Networksdocker-compose down –volumesRemoves containers, networks, and volumes created by up.
Docker Compose

Docker Volumes: Creating and Using Volumes

TaskCommandDescription
Create a Volumedocker volume create <volume_name>Creates a new named volume.
List Volumesdocker volume lsLists all Docker volumes on the system.
Inspect a Volumedocker volume inspect <volume_name>Provides detailed information about a specific volume.
Mount a Volume to a Containerdocker run -d -v <volume_name>:/path/in/container <image_name>Mounts a volume to a specific path inside a container.
Mount a Host Directory as a Volumedocker run -d -v /path/on/host:/path/in/container <image_name>Mounts a host directory as a volume inside the container.
Remove a Volumedocker volume rm <volume_name>Removes a specific volume.
Remove Unused Volumesdocker volume pruneDeletes all volumes not used by at least one container.
Docker Volumes

Dockerfile: Basic Syntax and Best Practices

InstructionSyntaxDescription
Specify Base ImageFROM <image_name>:<tag>Defines the base image for the Dockerfile.
Set Working DirectoryWORKDIR /path/to/directorySets the working directory for subsequent instructions.
Copy Files to ContainerCOPY <source_path> <destination_path>Copies files from the host to the container’s filesystem.
Run Commands in ContainerRUN <command>Executes commands in the container during the build process (e.g., RUN apt-get update).
Set Environment VariablesENV <key>=<value>Defines environment variables inside the container.
Expose PortsEXPOSE <port_number>Specifies which ports the container listens on at runtime.
Define Default CommandCMD [“executable”, “param1”, “param2”]Sets the default command to run when the container starts.
Set Build ArgumentsARG <variable_name>=<default_value>Defines variables that users can pass at build-time (e.g., ARG version=latest).
Best Practice: Use .dockerignore.dockerignoreUse a .dockerignore file to exclude files and directories from being copied into the image.
Best Practice: Minimize LayersCombine commands like RUN apt-get update && apt-get install -y <package>Reduces the number of layers in the image, improving efficiency.
Dockerfile

Useful Tips and Best Practices

Debugging Containers

TaskCommand/PracticeDescription
Attach to a Running Containerdocker attach <container_name>Connects your terminal to a running container for real-time interaction.
Run a Container in Interactive Modedocker run -it <image_name> /bin/bashStarts a container and provides an interactive shell session.
Inspect Container Statedocker inspect <container_name>Provides detailed information about a container’s configuration and state.
Check Resource Usagedocker stats <container_name>Monitors real-time resource usage (CPU, memory, etc.) for containers.
View Container Logsdocker logs <container_name>Displays the logs generated by a container’s application.
Tail Container Logsdocker logs -f <container_name>Follows (tails) the logs of a running container in real-time.
Execute a Command in a Running Containerdocker exec -it <container_name> <command>Executes a specific command inside a running container.
Use Debugging Tools in ContainerUse images like alpine with RUN apk add –no-cache <package>Install debugging tools inside the container for troubleshooting.
Debugging Containers

Best Practices for Debugging Containers:

  • Use docker exec for On-the-Fly Debugging: This allows you to run commands in a running container without stopping it.
  • Leverage Multi-Stage Builds for Debugging: Include debugging tools only in the development stages of your Dockerfile.
  • Keep Logs Accessible: Configure containers to output logs to a location where they can be easily accessed and monitored.
  • Test Containers in Isolation: Ensure that containers work correctly on their own before integrating them into larger systems.

Managing Logs

TaskCommand/PracticeDescription
Configure Log Driverdocker run –log-driver=<driver> <image_name>Sets the logging driver (e.g., json-file, syslog) for a container.
Limit Log Sizedocker run –log-opt max-size=10m –log-opt max-file=3 <image_name>Limits log file size and sets a rotation policy.
Redirect Logs to Host Filedocker run -v /path/on/host:/path/in/container <image_name>Mounts a host directory for container logs.
View Logs for All Containersdocker logs –tail 100 -f $(docker ps -q)Shows the latest 100 lines of logs for all running containers.
Clear Logs`docker logs -f <container_name>tee /dev/null`
Managing Logs

Best Practices for Managing Logs:

  • Implement Log Rotation: Use log drivers with rotation policies to prevent logs from consuming excessive disk space.
  • Centralize Logs: Use a centralized logging system (e.g., ELK stack, Fluentd) to aggregate and analyze logs from multiple containers.
  • Monitor Log Levels: Configure different log levels (info, warning, error) to avoid clutter and focus on relevant information.
  • Regularly Review Log Storage: Ensure that log files do not grow indefinitely and are archived or rotated as needed.

Performance Tuning

TaskCommand/PracticeDescription
Limit CPU and Memory Usagedocker run –memory=”500m” –cpus=”1.0″ <image_name>Restricts the amount of memory and CPU a container can use.
Optimize Image SizeUse docker build –squashReduces image size by squashing layers during build.
Use Efficient Base ImagesFROM alpine:latestSelect minimal base images (e.g., Alpine) to reduce image size and improve performance.
Use Docker’s Resource LimitsConfigure resource limits in docker-compose.ymlSet limits in Compose files to manage resource allocation.
Monitor Container PerformanceUse docker stats or third-party monitoring toolsRegularly check resource usage and adjust as needed.
Performance Tuning

Best Practices for Performance Tuning:

  • Optimize Dockerfile: Minimize the number of layers and use multi-stage builds to keep images lean.
  • Adjust Resource Limits: Tailor CPU and memory limits based on application needs to ensure optimal performance.

Jenkins Cheat Sheet

Getting Started with Jenkins – Installation and Setup

TaskCommand/PracticeDescription
Install Jenkins`wget -q -O – https://pkg.jenkins.io/debian/jenkins.io.keysudo apt-key add -<br>echo deb http://pkg.jenkins.io/debian-stable binary
Start Jenkins Servicesudo systemctl start jenkinsStarts the Jenkins service.
Check Jenkins Statussudo systemctl status jenkinsChecks the status of the Jenkins service.
Access Jenkins Web InterfaceOpen http://localhost:8080 in a web browserAccess Jenkins’ web interface to complete setup.
Unlock JenkinsFollow instructions at http://localhost:8080 to retrieve the initial admin password from /var/lib/jenkins/secrets/initialAdminPasswordProvides initial setup instructions and admin password.
Upgrade Jenkinssudo apt-get updatesudo apt-get upgrade jenkinsUpgrades Jenkins to the latest version.
Installation And Setup

Overview of Jenkins Architecture and Components

ComponentDescription
Jenkins MasterThe central server that coordinates the build process. It manages jobs, schedules tasks, and provides the user interface.
Jenkins Agent (Slave)Machines configured to run build jobs dispatched by the Jenkins Master. They can run on various platforms and distribute the workload.
Build JobsThe core unit of work in Jenkins, defining tasks such as building software or running tests.
PipelinesDefine the entire build and deployment workflow as code using a Jenkinsfile, automating complex workflows.
PluginsExtend Jenkins’ functionality, including integrations with version control systems, build tools, and notifications.
Jenkins Architecture

Basic Jenkins Commands

TaskCommandDescription
Create a New JobThrough Web UI: Click “New Item”Initiates the creation of a new Jenkins job.
Build a JobClick “Build Now” in job viewStarts a build of the selected job.
Delete a JobThrough Web UI: Click “Delete Project”Removes a Jenkins job from the system.
Configure a JobThrough Web UI: Click “Configure”Opens the configuration page for a job.
Manage PluginsThrough Web UI: Go to “Manage Jenkins””Manage Plugins”Access the plugin management interface.
View Build HistoryThrough Web UI: Click on a job, then “Build History”Displays the history of builds for a job.
Pause/Resume a JobThrough Web UI: Click “Build Now” and “Pause” or “Resume”Manages job execution to control build activity.
Schedule a BuildIn Job Configuration: Set “Build Triggers”Configures periodic builds or builds triggered by SCM changes.
Basic Jenkins Commands

Advanced Jenkins Configuration

TaskCommand/PracticeDescription
Create a Pipeline JobThrough Web UI: Click “New Item””Pipeline”Creates a new pipeline job for advanced build processes.
Define a JenkinsfileWrite Jenkinsfile in the root of your repositoryDefines the build pipeline as code.
Integrate with GitThrough Web UI: Configure Source Code Management in job settingsConnects Jenkins to a Git repository for source code retrieval.
Integration with DockerInstall Docker pluginConfigure “Docker” in job settingsAllows Jenkins to build and deploy Docker containers.
Integration with KubernetesInstall Kubernetes pluginConfigure “Kubernetes” in job settingsManages Kubernetes clusters for scaling Jenkins builds.
Setup CI/CD PipelinesThrough Web UI: Define stages and steps in JenkinsfileAutomates the build, test, and deployment pipeline.
Install Jenkins PluginsThrough Web UI: Go to “Manage Jenkins””Manage Plugins”Adds functionality to Jenkins by installing plugins.
Configure Global SecurityThrough Web UI: Go to “Manage Jenkins””Configure Global Security”Configures security settings, including user roles and permissions.
Backup Jenkins ConfigurationManually backup /var/lib/jenkins or use plugins like “ThinBackup”Ensures you have a backup of Jenkins data and configurations.
Advanced Configuration

Creating and Configuring Jobs

TaskCommand/PracticeDescription
Create a New Freestyle JobThrough Web UI: Click “New Item””Freestyle project”Sets up a new freestyle project for simple builds.
Create a New Pipeline JobThrough Web UI: Click “New Item””Pipeline”Creates a new pipeline job for complex workflows.
Configure Job TriggersIn Job Configuration: Set “Build Triggers”Defines triggers for automated builds, like SCM polling.
Set Up Build StepsIn Job Configuration: Define “Build” stepsAdds steps to build, test, and deploy the project.
Add Post-Build ActionsIn Job Configuration: Define “Post-build Actions”Configures actions to perform after the build completes.
Configure NotificationsIn Job Configuration: Set “Post-build Actions”Configures notifications to alert on build status changes.
Creating And Configuring Jobs

Managing Jenkins Pipelines: Setup and Execution

TaskCommand/PracticeDescription
Create a Pipeline JobThrough Web UI: Click “New Item””Pipeline”Creates a new pipeline job for advanced build processes.
Define Stages in JenkinsfileWrite stages in Jenkinsfile in the repositoryStructures the build pipeline into distinct stages.
Execute a Pipeline BuildClick “Build Now” in the pipeline job viewStarts the pipeline build process.
View Pipeline ExecutionThrough Web UI: Click on a pipeline job, then “Pipeline Steps”Monitors the execution and stages of the pipeline.
Manage Pipeline ParametersIn Pipeline Configuration: Define parametersConfigures parameters to customize pipeline builds.
Pipeline VisualizationThrough Web UI: View “Pipeline Graph”Provides a visual representation of pipeline execution.
Managing Jenkins Pipelines

Jenkinsfile: Syntax and Best Practices

AspectDescriptionExample
Basic SyntaxDefines the pipeline stages and steps in code.pipeline { … }
Declarative PipelineProvides a structured format for defining pipelines.pipeline { agent any stages { stage(‘Build’) { steps { echo ‘Building…’} } } }
Scripted PipelineOffers a more flexible, programmatic approach.node { stage(‘Build’) { echo ‘Building…’} }
Environment VariablesUse environment block to define variables.environment { MY_VAR = ‘value’ }
Error HandlingUse try/catch for handling errors.try { … } catch { … }
Parallel StagesRun stages in parallel for efficiency.stages { stage(‘Parallel’) { parallel { stage(‘A’) { … } stage(‘B’) { … } } } }
Version ControlStore Jenkinsfile in version control for consistency.Jenkinsfile in Git repository.
Jenkinsfile

Maintenance Tips

TaskCommand/PracticeDescription
Backup and Restore StrategiesUse plugins like “ThinBackup”Manual backup of /var/lib/jenkinsEnsures Jenkins data and configurations are preserved.
Monitoring Jenkins PerformanceInstall monitoring plugins like “Prometheus”Tracks and analyzes Jenkins performance metrics.
Securing Jenkins: User Roles and PermissionsThrough Web UI: Go to “Manage Jenkins””Configure Global Security”Manages user roles, permissions, and security settings.
Maintenace Tips

Git Cheat Sheet

Basic Git Commands

TaskCommandDescription
Installation and SetupInstallation varies by OSFollow specific installation instructions for your operating system.
Clone a Repositorygit clone <repo-url>Creates a local copy of a remote repository.
Initialize a New Repositorygit initInitializes a new Git repository in the current directory.
Check Repository Statusgit statusDisplays the status of changes in the working directory.
View Commit Historygit logShows the commit history for the repository.
Add Changes to Staging Areagit add <file>git add .Adds specified files or all files to the staging area.
Commit Changesgit commit -m “message”Commits staged changes with a descriptive message.
Push Changes to Remote Repositorygit push origin <branch>Pushes commits to the specified branch on a remote repository.
Pull Changes from Remote Repositorygit pull origin <branch>Fetches and merges changes from the remote repository to the local branch.
Create a New Branchgit branch <branch-name>Creates a new branch in the repository.
Switch to a Branchgit checkout <branch-name>Switches to the specified branch.
Merge Branchesgit merge <branch-name>Merges changes from the specified branch into the current branch.
Delete a Branchgit branch -d <branch-name>Deletes the specified branch.
Basic Git Commands

Advanced Git Operations

TaskCommandDescription
Merging Branchesgit merge <branch-name>Merges the specified branch into the current branch.
Rebasinggit rebase <branch-name>Re-applies commits from the current branch onto the specified branch.
Resolve Merge ConflictsEdit conflicting filesgit add <file>git commitManually resolve conflicts, add resolved files, and commit.
Create a Taggit tag <tag-name>Creates a new tag pointing to the current commit.
List Tagsgit tagLists all tags in the repository.
Delete a Taggit tag -d <tag-name>Deletes a tag from the local repository.
Fetch Changes from Remotegit fetch originRetrieves updates from the remote repository but does not merge.
Pull Changes from Remotegit pull origin <branch>Fetches and merges changes from the remote branch into the local branch.
Push Changes to Remotegit push origin <branch>Pushes commits from the local branch to the remote branch.
Advanced Git Operations

Collaboration Tips

  • Git Workflows
    • Gitflow: Utilizes a structured approach with branches like master, develop, and feature branches for managing releases and features.
    • Feature Branches: Develop new features or fixes in separate branches to keep the main branch stable.
    • Pull Requests: Use pull requests to review and merge changes, ensuring code quality and collaboration.
  • Managing Large Repositories with Git LFS (Large File Storage)
    • Install Git LFS: git lfs install
    • Track Large Files: git lfs track “*.filetype”
    • Add and Commit: Use standard Git commands; Git LFS manages the large files.
    • Push and Pull: Use git push and git pull as usual; Git LFS handles the large files separately.
  • Handling Submodules
    • Add Submodule: git submodule add <repo-url> <path>
    • Update Submodule: git submodule update –remote
    • Remove Submodule: Edit .gitmodules and .git/config to remove references, then delete the submodule directory.

Best Practices for Integration

  1. CI/CD Pipeline Setup
    • Jenkins Pipeline Configuration
      • Define pipeline stages: Build, Test, Deploy.
      • Use Jenkins Pipelines (Declarative or Scripted) for automation.
    • Docker Integration
      • Build and tag Docker images in Jenkins.
      • Optimize Dockerfiles to reduce image size and build time.
    • Kubernetes Deployment
      • Deploy Docker containers using Kubernetes manifests or Helm charts.
      • Configure Kubernetes for scaling and managing applications.
  2. Version Control with Git
    • Branching Strategy
      • Implement strategies like Gitflow or GitHub Flow for feature development and releases.
    • Commit and Pull Requests
      • Use clear commit messages and enforce code reviews through pull requests.
    • Merge and Conflict Resolution
      • Handle merge conflicts carefully and review changes before merging.
  3. Containerization and Orchestration
    • Security and Optimization
      • Regularly scan Docker images for vulnerabilities.
      • Use environment variables for configuration; avoid hardcoding sensitive data.
    • Resource Management
      • Define resource requests and limits in Kubernetes to manage cluster resources efficiently.
  4. Infrastructure as Code (IaC)
    • Provisioning
      • Use tools like Terraform or Ansible for automated infrastructure provisioning.
    • Version Control
      • Store IaC scripts in Git repositories to track changes and maintain consistency.
  5. Continuous Testing
    • Integration in Pipeline
      • Incorporate automated tests into the Jenkins pipeline (unit, integration, end-to-end).
    • Test Coverage
      • Monitor and aim for high test coverage to identify issues early.
  6. Monitoring and Logging
    • Centralized Logging
      • Aggregate logs using solutions like ELK Stack or Fluentd.
    • Performance Monitoring
      • Collect and visualize metrics using tools like Prometheus and Grafana.
  7. Security Practices
    • Access Control
      • Implement role-based access controls (RBAC) in Jenkins, Docker, and Kubernetes.
    • Secrets Management
      • Use secure methods for managing secrets, such as Kubernetes Secrets or encrypted environment variables.

Conclusion

Docker, Kubernetes, Jenkins, and Git each play a crucial role in modern DevOps practices. Docker facilitates consistent environments through containerization, Kubernetes manages and scales these containers, Jenkins automates CI/CD pipelines, and Git provides robust version control and collaboration.

These tools collectively streamline development processes, ensure consistency across environments, and enhance scalability and collaboration, driving efficiency and reliability in software delivery.

Resources

  1. Docker Ecosystem: Docker Ecosystem – Docker is a containerization platform, quickly gaining ground in DevOps as a one-stop solution for all development needs.
  2. Docker Cleanup: Docker cleanup quick tutorial – This quick tutorial shows the different ways to rid your system of unused and unnecessary Docker files and enable smoother system performance.
  3. Microservice Architecture in Docker: Building apps using Microservice Architecture in Docker – Docker has many pros but comes with unique cons. Learn how to use Microservice in Docker with tutorial!
  4. Docker Documentation: https://docs.docker.com – The official Docker documentation provides comprehensive guides, tutorials, and reference material to help you get started with Docker and its advanced features.
  5. Jenkins User Documentation: https://www.jenkins.io/doc/ – Jenkins offers detailed documentation on installing, configuring, and using Jenkins for continuous integration and continuous delivery (CI/CD).
  6. Pro Git Book: https://git-scm.com/book/en/v2 – This free, open-source book is a great resource for mastering Git, from basic concepts to advanced techniques.

Ashwini Dave

Ashwini Dave, an accomplished digital marketer specializing in SEO and groundbreaking campaigns. With an MBA in Marketing, she crafts strategic, high-impact results. A tech enthusiast exploring AI and cutting-edge tech, Ashwini seamlessly integrates innovation into her marketing strategies. Outside the digital sphere, she is an avid traveler, finding inspiration in nature's beauty while exploring the world.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button