Skip to main content

DOCKER PART -1 Basic Commands

 

Great! Let's start with the basics of Docker commands. First, we’ll verify that Docker is installed and running correctly on your system.

Step 1: Verify Docker Installation and Get Version Information

  1. Check Docker Version
    Run the following command to ensure Docker is installed and to see the version:

    bash

    docker --version

    Example Output:


    Docker version 24.0.2, build 123456
  2. Check Docker Engine Status
    Use this command to confirm Docker is running:

    bash

    docker info

    This will provide detailed information about your Docker setup, such as the number of containers, images, and the server details.

  3. Test with Hello World Container
    Run this command to test if Docker is working properly:

    bash

    docker run hello-world

    This pulls a small image named hello-world from Docker Hub and runs it. If successful, you'll see a message confirming Docker is installed and functioning.

Step 2: Basic Docker Commands for Images and Containers

1. Listing Docker Images

View all images available on your system:

bash

docker images

Example Output:


REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest d1165f221234 3 weeks ago 13kB

2. Pulling an Image

Download an image from Docker Hub (e.g., nginx):

bash

docker pull nginx

Example Output:

vbnet

Using default tag: latest latest: Pulling from library/nginx Digest: sha256:... Status: Downloaded newer image for nginx:latest

3. Running a Container

Run a container from an image:

bash

docker run nginx

This will start a container using the nginx image. If successful, the container will run but exit immediately because there’s no foreground task.

To run it interactively and keep it alive:

bash

docker run -d -p 8080:80 nginx
  • -d: Runs the container in detached mode (background).
  • -p 8080:80: Maps port 8080 on your machine to port 80 inside the container.

Open your browser and visit http://localhost:8080 to see the Nginx welcome page.

4. Listing Running Containers

View all currently running containers:

bash

docker ps

Example Output:

bash

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES abc12345 nginx "/docker-entrypoint.…" 5 seconds ago Up 3 seconds 0.0.0.0:8080->80/tcp nostalgic_naming

5. Stopping a Container

Stop a running container using its CONTAINER ID or NAME (from docker ps):

bash

docker stop <CONTAINER_ID_OR_NAME>

6. Removing a Container

Remove a stopped container:

bash

docker rm <CONTAINER_ID_OR_NAME>

Step 3: Managing Containers with Crucial Flags Explained

1. Running Containers with Names

By default, Docker assigns random names to containers. You can specify a name for better management:

bash

docker run --name my_nginx -d -p 8080:80 nginx

Explanation of flags:

  • --name my_nginx: Assigns a custom name (my_nginx) to the container.
  • -d: Runs the container in detached mode (in the background).
  • -p 8080:80: Maps port 8080 on your local machine to port 80 inside the container, allowing access via http://localhost:8080.

2. Viewing All Containers

List both running and stopped containers:

bash

docker ps -a

Explanation of flags:

  • -a: Displays all containers, including those that have stopped.

3. Starting a Stopped Container

Restart a stopped container:

bash

docker start my_nginx
  • This restarts the container without re-creating it.

4. Accessing a Running Container

Use an interactive shell inside a running container:

bash

docker exec -it my_nginx bash

Explanation of flags:

  • exec: Executes a command in a running container.
  • -it: Combines -i (interactive mode) and -t (allocates a pseudo-terminal) to interact with the container via a shell.

Once inside, you can run commands like ls, cd, or view configuration files. Type exit to leave the container.

5. Stopping and Removing Containers

Stop and remove containers with a single command:

bash

docker rm -f my_nginx

Explanation of flags:

  • -f: Forcefully stops and removes a running container.

6. Inspecting a Container

Get detailed information about a container:

bash

docker inspect my_nginx

This outputs JSON data, including network settings, environment variables, and resource usage.

While both docker run -it and docker exec -it involve interacting with containers, they are not the same. Let me clarify the difference:

1. docker run -it firstdocker bash

  • Purpose: Used to create and start a new container interactively from an image.

  • Key Characteristics:

    • It starts a brand-new container from the specified image (firstdocker in this case).
    • The -it flags make the container interactive, allowing you to access its terminal.
    • The command (bash) specifies the shell to run inside the container.
  • Scenario: This is useful when you want to launch a new container and immediately interact with it.

    Example Workflow:

    bash

    docker run -it ubuntu bash
    • This creates a new container from the ubuntu image.
    • Once inside, you can run Linux commands in the interactive shell.

2. docker exec -it my_nginx bash

  • Purpose: Used to execute a command inside an already running container.

  • Key Characteristics:

    • It does not create a new container; instead, it attaches to an existing container (my_nginx in this case).
    • The bash command opens an interactive shell in the specified running container.
  • Scenario: This is useful when you need to debug, explore, or interact with a running container without stopping or restarting it.

    Example Workflow:

    bash

    docker exec -it my_nginx bash
    • This connects you to the terminal of the already-running my_nginx container.

SDK version of Commands that we learned till now:

python

import docker # Initialize Docker client client = docker.from_env() # Step 1: Verify Docker Installation and Engine Status print("Docker Version:") print(client.version()) print("\nDocker Info:") print(client.info()) # Step 2: Test with Hello World Container print("\nRunning Hello World container...") hello_container = client.containers.run("hello-world", detach=False) print("Hello World container output retrieved.") # Step 3: Basic Docker Commands for Images and Containers # 1. Listing Docker Images print("\nListing Docker Images:") for image in client.images.list(): print(image.tags) # 2. Pulling an Image print("\nPulling nginx Image...") nginx_image = client.images.pull("nginx") print("Pulled Image Tags:", nginx_image.tags) # 3. Running a Container print("\nRunning nginx container...") nginx_container = client.containers.run( "nginx", detach=True, ports={"8080/tcp": 8080}, name="my_nginx" ) print(f"nginx Container ID: {nginx_container.id}") # 4. Listing Running Containers print("\nListing Running Containers:") for container in client.containers.list(): print(f"Container ID: {container.id}, Image: {container.image.tags}") # 5. Stopping a Container print("\nStopping nginx container...") nginx_container.stop() print("nginx container stopped.") # 6. Removing a Container print("\nRemoving nginx container...") nginx_container.remove() print("nginx container removed.") # Step 4: Managing Containers with Crucial Flags # 1. Running Container with a Name print("\nRunning a named nginx container...") named_container = client.containers.run( "nginx", detach=True, ports={"8080/tcp": 8080}, name="my_named_nginx" ) print(f"Named nginx Container ID: {named_container.id}") # 2. Viewing All Containers print("\nListing All Containers (Including Stopped):") for container in client.containers.list(all=True): print(f"Container ID: {container.id}, Status: {container.status}, Name: {container.name}") # 3. Starting a Stopped Container print("\nStarting a stopped nginx container...") named_container.start() print("Named nginx container started.") # 4. Accessing a Running Container print("\nAccessing a running nginx container:") exec_output = named_container.exec_run("ls") print("Files in the nginx container root directory:") print(exec_output.output.decode()) # 5. Stopping and Removing a Container print("\nForce-stopping and removing the named nginx container...") named_container.remove(force=True) print("Named nginx container forcefully removed.") # 6. Inspecting a Container print("\nInspecting the nginx container...") # Inspecting works on previously created containers, assuming there's a valid one to inspect # Uncomment and replace 'my_named_nginx' with a valid container name if needed # print(client.containers.get("my_named_nginx").attrs)

Step 4: Managing Docker Images

1. Listing Images

View all images stored on your system:

bash

docker images

Explanation of columns:

  • REPOSITORY: The image's name (e.g., nginx).
  • TAG: The version of the image (e.g., latest).
  • IMAGE ID: A unique identifier for the image.
  • CREATED: When the image was built.
  • SIZE: Size of the image.

2. Removing an Image

Delete an image by its ID or name:

bash

docker rmi <IMAGE_ID_OR_NAME>

If the image is being used by any container, you’ll get an error. Use the -f flag to force removal:

bash

docker rmi -f <IMAGE_ID_OR_NAME>

3. Pulling Images

Download an image from Docker Hub or another registry:

bash

docker pull <IMAGE_NAME>:<TAG>

Example:

bash

docker pull ubuntu:20.04
  • If no tag is specified, Docker defaults to :latest.

4. Building a Custom Image

You can create your own image using a Dockerfile:

  1. Create a file named Dockerfile with the following content:
    Dockerfile

    FROM ubuntu:20.04 RUN apt-get update && apt-get install -y curl CMD ["bash"]
  2. Build the image:
    bash

    docker build -t my_custom_image .
    Explanation of flags:
    • -t: Assigns a tag/name to the image (my_custom_image).
    • .: Specifies the build context (current directory).

5. Inspecting an Image

Get detailed metadata about an image:

bash

docker inspect <IMAGE_ID_OR_NAME>

This displays details such as layers, creation date, and configuration.


6. Saving and Loading Images

  • Save an Image to a File:
    bash

    docker save -o my_image.tar <IMAGE_ID_OR_NAME>
  • Load an Image from a File:
    bash

    docker load -i my_image.tar

If you have multiple Dockerfiles in your folder and want to build an image based on a specific file, you should use the -f (or --file) flag with the docker build command to specify which Dockerfile to use.

Syntax:

sh

docker build -t <image_name> -f <Dockerfile_path> <context>

Example:

Assume your folder contains:

bash

/my-project ├── Dockerfile.dev ├── Dockerfile.prod ├── app/ ├── requirements.txt

To build an image using Dockerfile.dev:

sh

docker build -t my-dev-image -f Dockerfile.dev .

To build an image using Dockerfile.prod:

sh

docker build -t my-prod-image -f Dockerfile.prod .

Explanation:

  • -t my-dev-image: Tags the built image as my-dev-image
  • -f Dockerfile.dev: Specifies the Dockerfile to use
  • .: The build context (current directory)

While save and load are used for images, export and import work for containers:

  • Export a Running/Stoppable Container:

    bash

    docker export -o my_container.tar <CONTAINER_ID>

    This saves the container’s filesystem as a .tar file.

  • Import as a New Image:

    bash

    docker import my_container.tar new_image_name

Comments