If you’re already familiar with Docker and use this powerful containerization tool, you might not yet know about the docker run -it --rm command. This command is extremely useful for testing and development, providing an efficient way to interact with containers and keep your environment clean. In this post, we’ll explore in detail how this command works and present some practical examples to help you start using it.

What is the docker run -it --rm Command?

The docker run command is used to create and start a new container from a Docker image. The -it and --rm options add specific functionalities that make the command particularly useful in certain situations.

-i (interactive): Keeps the standard input (stdin) open, allowing interaction with the container.
-t (tty): Allocates a pseudo-TTY, which is essential for providing an interactive terminal interface.
--rm (remove): Automatically removes the container when it is stopped, freeing up resources and preventing the accumulation of stopped containers.

Why Use docker run -it --rm?

This command is particularly useful for testing and development, where you need to interact with the container and don't want to worry about manually cleaning up containers afterward. It helps keep your Docker environment clean and efficient.

Practical Examples

1. Running an Interactive Ubuntu Container

docker run -it --rm ubuntu

This command pulls the Ubuntu image (if not already available locally), starts an interactive container, and opens a bash terminal inside it. When you exit the terminal, the container is automatically removed.

2. Testing a CLI Tool

docker run -it --rm node:latest node

Here, we are running the Node.js CLI inside a container. This is useful for quickly testing commands and scripts without needing to install Node.js locally.

3. Running a Python Script

First, create a script.py file with the following content:

print("Hello from Docker!")

Then, run the command:

docker run -it --rm -v "$PWD":/usr/src/app -w /usr/src/app python:3.9 python script.py

This command mounts the current directory ($PWD) into the container, sets the working directory to /usr/src/app, and runs the Python script.

Conclusion

The docker run -it --rm command is a powerful and versatile tool in the Docker arsenal, facilitating quick tests and interaction with containers without the need for manual cleanup. Try out the examples above and see how it can optimize your workflow.