Essential Docker Commands
1. List Running Containers:
To see all active containers, use:

docker ps

To view all containers (including stopped ones):

docker ps -a

2. Start and Stop Containers:
To start a stopped container:

docker start container-name-or-id

To stop a running container:

docker stop container-name-or-id

3. Remove Containers:
To delete a stopped container:

docker rm container-name-or-id

To forcefully remove a running container:

docker rm -f container-name-or-id

4. Inspect Containers:
To view detailed information about a container:

docker inspect container-name-or-id

5. View Logs:
To view logs for a container:

docker logs container-name-or-id

Use `-f` to follow logs in real-time.

6. Execute Commands Inside Containers:
To run a command inside a container:

docker exec -it container-name-or-id command

For example, to open a bash shell:

docker exec -it container-name-or-id bash

Best Practices for Managing Containers
1. Name Your Containers:
Assign meaningful names to containers using the `--name` flag when creating or running them:

docker run --name my-nginx-container -d nginx

This makes it easier to identify and manage containers.

2. Monitor Resource Usage:
Keep an eye on container resource consumption using:

docker stats

This command displays CPU, memory, and network usage for all running containers.

3. Use Volumes for Data Persistence:
Store data outside containers using Docker volumes. This ensures that data persists even if a container is removed:

docker run -v /host/path:/container/path my-image

4. Limit Container Resources:
Prevent a single container from consuming excessive resources by setting limits:

docker run --memory="512m" --cpus="1.0" my-image

5. Automate Cleanup:
Use the `--rm` flag to automatically remove containers after they stop:

docker run --rm my-image

6. Secure Containers:
Avoid running containers with root privileges unless necessary. Use the `--user` flag to specify a non-root user:

docker run --user 1000:1000 my-image

Common Scenarios
Here are some practical examples to reinforce container management concepts:

1. Restarting a Crashed Application:

docker restart container-name-or-id

2. Backing Up Data:

docker cp container-name-or-id:/container/path /host/path

3. Debugging a Container:

docker exec -it container-name-or-id bash

4. Cleaning Up Unused Containers:

docker container prune

Conclusion
Managing containers effectively is vital for maintaining a streamlined and efficient Docker environment. By mastering essential commands and adopting best practices, you can ensure that your containers are well-organized, secure, and performant. With these tools at your disposal, you’re ready to take full advantage of Docker’s capabilities in real-world scenarios.