Work with a Docker container

Category : Kubernetes | Sub Category : Kubernetes With Java | By Prasad Bonam Last updated: 2023-11-21 10:37:05 Viewed : 231


Working with a Docker container involves several common operations such as creating, starting, stopping, and removing containers. Lets go through these basic operations using the example of the Spring Boot application container we created earlier:

  1. Create and Start a Container:

    bash
    docker run -p 8080:8080 my-spring-app:1.0

    This command creates and starts a container based on the my-spring-app:1.0 image. It maps port 8080 on the host to port 8080 on the container.

  2. Access the Application:

    Open a web browser and navigate to http://localhost:8080. You should see the output of your Spring Boot application.

  3. View Running Containers:

    bash
    docker ps

    This command lists the running containers. You should see your container in the list.

  4. Stop the Container:

    bash
    docker stop <container_id>

    Replace <container_id> with the actual container ID from the docker ps command. Stopping a container gracefully shuts down the application within the container.

  5. Restart the Container:

    bash
    docker start <container_id>

    If you stopped the container and want to start it again, use the docker start command.

  6. View All Containers (Including Stopped Ones):

    bash
    docker ps -a

    This command lists all containers, including those that are stopped.

  7. Remove the Container:

    bash
    docker rm <container_id>

    This command removes a stopped container. Replace <container_id> with the actual container ID. If the container is still running, use docker stop before docker rm.

  8. Remove All Stopped Containers:

    bash
    docker container prune

    This command removes all stopped containers at once.

  9. Execute Commands Inside a Running Container:

    bash
    docker exec -it <container_id> /bin/bash

    This command allows you to execute commands inside a running container. Replace <container_id> with the actual container ID.

These are some of the basic operations you might perform with Docker containers. Depending on your use case, you might need additional functionality, such as managing container networks, volumes, or interacting with container logs. Docker provides a comprehensive set of commands to manage containers, and you can explore more options in the official Docker documentation.

Search
Related Articles

Leave a Comment: