RMS Meta

RMS Meta

Code to cloud for people & nature

Blog · Dec 25, 2025

Running Commands Inside Docker Containers: Practical Guide

Sometimes you need to peek inside a running container: check logs, run a migration, or debug an issue. Here’s how to run commands inside Docker containers safely and predictably.

List containers and pick a target

# running containers
docker ps

# include stopped
docker ps -a

Run a one-off command in a new container

docker run --rm -it ubuntu:22.04 bash    # interactive shell
docker run --rm busybox echo "hello"      # single command

Tips: Use --rm to clean up automatically; add -v for volume mounts or --network to join a network.

Exec into an existing container

# interactive shell (bash or sh)
docker exec -it <container_id_or_name> bash
docker exec -it <container_id_or_name> sh

# run a single command
docker exec -it <container> ls /app
docker exec -it <container> env

When to use: Quick inspection or maintenance tasks without restarting the container.

Check logs without exec

docker logs <container>          # all logs
docker logs -f <container>        # follow
docker logs --tail 100 <container>

User, workdir, and env overrides

docker exec -it -u root <container> bash     # run as root
docker exec -it -w /app <container> ls        # set working dir
docker exec -it -e DEBUG=1 <container> env    # set env var

Copy files in or out

docker cp <container>:/path/in/container ./local-path
docker cp ./local-file <container>:/app/local-file

Common debugging commands

  • ps aux — see running processes
  • netstat -tulpn or ss -tulpn — check listening ports
  • curl / wget — hit local endpoints
  • env — inspect environment variables
  • ls -lah / cat — inspect files

Safety tips

  • Use a non-root user inside the image; only exec as root when necessary.
  • Prefer logs and metrics first; exec is for targeted inspection.
  • For production, avoid making ad-hoc changes inside containers—fix via image or config and redeploy.
  • Keep .dockerignore tidy to avoid shipping secrets; don’t copy secrets in via exec.

With these commands, you can inspect and troubleshoot containers quickly while keeping your environments reproducible and secure.