Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #91: Exec into a Container as Root without Sudo or a Password

docker-tips-and-tricks.jpg

This is handy when you configured your Dockerfile to run as a non-root user but you need to temporarily debug or test something out.

Prefer video? Here’s a recorded version of this tip on YouTube that shows a demo of what’s written below and more.

It’s way easier than you might expect and it doesn’t require using sudo or knowing / setting a root password! You can run your project however you see fit, such as with Docker Compose or straight up Docker. Then exec into your container as root even if you have USER someone defined in your Dockerfile:

# Here's how to do it with Docker Compose:
docker-compose exec -u root [SERVICE] bash

# Here's how to do it with Docker:
docker container exec -it -u root [CONTAINER] bash

This should work on most Linux based images. Technically using -u 0 works too because on Linux systems the 0 user id is often associated to the root user. In practice I tend to use root instead of 0 since it hasn’t failed yet on any Debian based Docker image and I’m only doing this in development for 1 off debugging sessions.

Now you can install system packages or mess with root files to troubleshoot whatever you’re working on without having to resort to modifying your Dockerfile and rebuilding your image for a temporary debug session.

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.



Comments