Docker

Docker: A Platform for Containerization

Docker is a popular platform that simplifies the process of building, shipping, and running applications in containers. It provides a standardized way to package and distribute applications, making it easier to deploy and manage them across different environments.

What are we using docker for?

Docker let’s you do a lot of things.It let’s you containerise your applications.It let’s you run other people’s code + packages in your machine.It let’s you run common software packages inside a container (For eg - Mongo, Postgres etc)

Where can we get packages from?

Just like you can push your code to Github/Gitlab.You can push images to docker registries

notion image

Common commands to know

  1. docker run

  2. docker ps

  3. docker kill

Running an image

1. Running a simple image

Let’s say you wan’t to run MongoDB locally https://hub.docker.com/_/mongo

docker run mongo

You will notice you can’t open it in MongoDB Compass .

notion image

Adding a port mapping

The reason is that you haven’t added a port mapping

docker run  -p 27017:27017 mongo
notion image

Starting in detached mode

Adding -d will ensure it starts in the background

docker run -d -p 27017:27017 mongo

Inspecting a container

docker ps

This will show you all the containers you are running.

Stopping a container

docker kill <container_id>

Will stop the container that you are running In the end, this is the flow of commands -

notion image

Common packages

Mongo

docker run -d -p 27017:27017 mongo

Postgres

docker run -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres

The connection string for this postgres would be

postgresql://postgres:mysecretpassword@localhost:5432/postgres
Code to test it out
// Import the pg library
const { Client } = require('pg');

// Define your connection string (replace placeholders with your actual data)
const connectionString = 'postgresql://postgres:mysecretpassword@localhost:5432/postgres';

// Create a new client instance with the connection string
const client = new Client({
  connectionString: connectionString
});

// Connect to the database
client.connect(err => {
  if (err) {
    console.error('connection error', err.stack);
  } else {
    console.log('connected to the database');
  }
});

// Run a simple query (Example: Fetching the current date and time from PostgreSQL)
client.query('SELECT NOW()', (err, res) => {
  if (err) {
    console.error(err);
  } else {
    console.log(res.rows[0]);
  }

  // Close the connection
  client.end();
});

Key Concepts

  • Containers: A container is a lightweight, standalone unit that packages an application and its dependencies into a single, portable artifact. It includes everything the application needs to run, from the operating system to libraries and configuration settings.

  • Images: Docker images are read-only templates that serve as the basis for creating containers. They contain the application code, dependencies, and configuration files.

  • Dockerfile: A Dockerfile is a text document that contains instructions for building a Docker image. It specifies the base image, dependencies, and commands needed to create the container.

Benefits of Docker

  • Portability: Containers can be easily moved and run on different environments, from development machines to production servers.

  • Efficiency: Containers are lightweight and start up quickly, making them ideal for microservices architectures.

  • Isolation: Each container runs in its own isolated environment, preventing conflicts between applications.

  • Scalability: Docker makes it easy to scale applications horizontally by adding more containers.

  • Consistency: Docker ensures that applications run consistently across different environments, reducing the risk of errors.

How Docker Works

  1. Create a Dockerfile: Define the instructions for building your container image in a Dockerfile.

  2. Build the Image: Use the docker build command to create the image from the Dockerfile.

  3. Run the Container: Use the docker run command to start a container based on the image.

  4. Manage Containers: Use Docker commands to start, stop, restart, and remove containers.

Use Cases for Docker

  • Microservices Architecture: Docker is ideal for building and deploying microservices applications, as it allows you to package each microservice into its own container.

  • Continuous Integration/Continuous Deployment (CI/CD): Docker can be used to automate the building, testing, and deployment of applications.

  • Application Development: Developers can use Docker to create isolated development environments, ensuring that their code runs consistently.

  • Cloud Deployment: Docker can be used to deploy applications to cloud platforms like AWS, Azure, and GCP(google cloud provider).

In summary, Docker is a powerful tool for modern application development and deployment. By providing a standardized way to package and distribute applications, Docker simplifies the development process and improves portability, efficiency, and scalability.

Windows:

  1. Download Docker Desktop: Visit the official Docker website (https://www.docker.com/) and download the latest Docker Desktop for Windows installer.

  2. Install Docker Desktop: Double-click the installer and follow the on-screen instructions. By default, Docker Desktop will install WSL2 for optimal performance.

  3. Verify Installation: Open a command prompt or PowerShell and run the following command:Bash

    docker run hello-world

    If Docker is installed correctly, you should see a message indicating a successful container run.

  4. if you want to start container

docker run image

macOS:

  1. Download Docker Desktop: Visit the official Docker website (https://www.docker.com/) and download the latest Docker Desktop for macOS installer.

  2. Install Docker Desktop: Double-click the installer and follow the on-screen instructions.

  3. Verify Installation: Open a Terminal and run the following command:Bash

    docker run hello-world

    If Docker is installed correctly, you should see a message indicating a successful container run.

Additional Tips:

  • Check for Updates: Regularly update Docker Desktop to ensure you have the latest features and security fixes.

  • Configure WSL2 (Windows only): If you're using WSL2, ensure it's enabled and configured correctly. You can find instructions on the Docker documentation.

  • Troubleshoot Issues: If you encounter any problems, refer to the Docker documentation or community forums for troubleshooting tips.

  • Consider Docker Desktop Alternatives: While Docker Desktop is a popular choice, there are other options available, such as Docker Toolbox for older Windows systems or standalone Docker installations on both Windows and macOS.

By following these steps and considering the additional tips, you should be able to successfully install Docker on your Windows or macOS system and start using it for containerization.

Common Docker Commands

https://github.com/shaikhshahbaz4022/Docker

Here are some of the most frequently used Docker commands:

Image Management

  • docker pull <image_name>:<tag>: Pulls an image from a Docker registry (e.g., Docker Hub).

  • docker push <image_name>:<tag>: Pushes an image to a Docker registry.

  • docker build -t <image_name>:<tag> .: Builds an image from a Dockerfile in the current directory.

  • docker images: Lists all images on your system.

  • docker rmi <image_name>:<tag>: Removes an image.

Container Management

  • docker run <image_name>:<tag>: Creates and starts a container from an image.

  • docker ps: Lists running containers.

  • docker ps -a: Lists all containers, including stopped ones.

  • docker start <container_id>: Starts a stopped container.

  • docker stop <container_id>: Stops a running container.

  • docker restart <container_id>: Restarts a container.

  • docker rm <container_id>: Removes a container.

  • docker exec -it <container_id> <command>: Executes a command inside a running container.

Network Management

  • docker network create <network_name>: Creates a new network.

  • docker network ls: Lists all networks.

  • docker network rm <network_name>: Removes a network.

Volume Management

  • docker volume create <volume_name>: Creates a new volume.

  • docker volume ls: Lists all volumes.

  • docker volume rm <volume_name>: Removes a volume.

Other Commands

  • docker compose up: Starts multiple containers defined in a docker-compose.yml file.

  • docker-machine ls: Lists Docker machines (remote Docker hosts).

  • docker login: Logs in to a Docker registry.

Here are some key reasons why developers use Docker:

  • Portability: Docker containers can be run on any system that supports Docker, making it easy to move applications between different environments (development, testing, production).

  • Consistency: Docker ensures that applications run consistently across different environments, reducing the risk of errors due to differences in configuration or dependencies.

  • Efficiency: Containers are lightweight and start up quickly, making them ideal for microservices architectures and other applications that require fast deployment and scaling.

  • Isolation: Each container runs in its own isolated environment, preventing conflicts between applications.

  • Scalability: Docker makes it easy to scale applications horizontally by adding or removing containers as needed.

  • Automation: Docker can be integrated with continuous integration/continuous deployment (CI/CD) pipelines to automate the building, testing, and deployment of applications.

Docker is used for various purposes, including:

  • Development: Creating isolated development environments for different projects or teams.

  • Testing: Running automated tests in consistent environments.

  • Deployment: Deploying applications to production servers.

  • Microservices Architecture: Building and managing microservices-based applications.

  • Cloud Deployment: Deploying applications to cloud platforms like AWS, Azure, and GCP.

According to surveys, Docker is widely used by developers:

  • A significant majority of developers use Docker for application development and deployment.

  • Docker is particularly popular for microservices architectures and cloud-native applications.

In conclusion, Docker is a valuable tool for developers who want to build, ship, and run applications efficiently and consistently. It offers numerous benefits, including portability, consistency, efficiency, isolation, scalability, and automation.

Last updated

Was this helpful?