When working with Docker containers, many developers wonder:
“What is the root password inside a container?” or “How do I set one?”
This question usually arises when trying to exec into a container and switch users with su or when configuring a service that expects a root login.
Let’s break it down.
1️⃣ Does a Docker Container Have a Root Password?
- Yes, containers have a
rootuser by default. - No password is set by default unless explicitly configured.
That’s why if you try:docker exec -it mycontainer bash su -you’ll likely get:su: Authentication failure - That’s because root doesn’t need a password inside the container — you’re already root when you enter it via
docker exec.
2️⃣ Why Root Access Works Differently in Docker
Docker is designed around process isolation, not full virtual machines.
When you run:
docker exec -it mycontainer bash
you’re typically logged in as root automatically (unless the container is configured to run as a non-root user).
So, in most cases, you don’t need a root password at all.
3️⃣ Setting a Root Password Inside a Container
If you really need a root password (for example, if you’re running ssh inside a container — though generally not recommended):
Option 1 — Use passwd
docker exec -it mycontainer bash
passwd root
You’ll be prompted to set a new password.
Option 2 — During Build (Dockerfile)
FROM ubuntu:20.04
RUN apt-get update && apt-get install -y passwd \
&& echo "root:mysecurepassword" | chpasswd
This sets the root password when building the image.
Option 3 — Docker Compose Environment Variables
Some official images (like MySQL, PostgreSQL, etc.) let you configure passwords using environment variables:
environment:
MYSQL_ROOT_PASSWORD: mysecurepassword
⚠️ This is not the Linux root password, but the database root password.
4️⃣ Security Considerations ⚠️
- Running containers with
sshand root passwords is considered a bad practice.
Instead, use:docker execfor shell access- Non-root users for running applications
- Docker secrets or environment variables for managing credentials
- If you must enable
sshwith root login:- Use strong passwords
- Restrict access
- Prefer key-based authentication
📌 Summary
- By default, Docker containers do not have a root password set.
- You usually don’t need one, since
docker execgives you root already. - If absolutely required, you can set it via
passwdinside the container or in a Dockerfile. - Best practice: avoid
sshand password-based root logins inside containers. Usedocker exec, non-root users, and Docker secrets instead.