Creating and Running Containers in Docker
Introduction
Docker containers allow you to package applications with their dependencies and run them in an isolated environment. This section covers how to create and run containers efficiently.
1. Running Your First Container
To start a simple container, use:
docker run hello-world
What Happens?
• Docker checks if the hello-world image is available locally.
• If not, it pulls the image from Docker Hub.
• A container is created and executed.
• It prints a “Hello from Docker!” message and exits.
2. Running Containers in Different Modes
a) Detached Mode (Background Execution)
docker run -d nginx
• The -d flag runs the container in detached mode.
• The container runs in the background without displaying logs.
b) Interactive Mode
Run a container with an interactive shell:
docker run -it ubuntu /bin/bash
• -it allows user interaction with the container.
• /bin/bash opens a command-line interface inside the container.
3. Listing and Managing Containers
a) Viewing Running Containers
To see currently running containers:
docker ps
b) Viewing All Containers (Including Stopped)
docker ps -a
4. Stopping and Removing Containers
a) Stopping a Running Container
docker stop <container_id_or_name>
b) Removing a Stopped Container
docker rm <container_id_or_name>
c) Force Removing a Running Container
docker rm -f <container_id_or_name>
5. Running Containers with Port Mapping
To map a container’s port to the host machine:
docker run -d -p 8080:80 nginx
• Maps port 80 of the containers to port 8080 of the host.
• Now, access http://localhost:8080 in a browser.
6. Running Containers with Named Volumes
To persist data, use volumes:
docker run -d -v my volume:/app/data ubuntu
• -v my volume:/app/data mounts a volume for data storage.
7. Executing Commands Inside a Running Container
To access a running container’s shell:
docker exec -it <container_id_or_name> /bin/bash
Conclusion
• Docker containers make it easy to run applications in an isolated environment.
• You can run them in interactive or detached modes.
• Containers can be managed using start, stop, remove, and inspect commands.
• Port mapping and volumes ensure flexibility and data persistence.