Sudo changes the PATH

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2022-05-26

On a production server, when I ran:

$ docker-compose down

It executed this command but subsequently failed because it needed more permissions. So, as per the usual protocol, I tried again with sudo:

$ sudo docker-compose down

But now I got the error: "sudo: docker-compose: command not found" Why?

The reason is that when you sudo, you get a pre-configured $PATH, which is (supposed to be) something like the root user's default path. Having not specified this, my docker-compose program was not in that list of directories given by this $PATH.

Way around 1: Specify the full path when using sudo

$ sudo /usr/local/bin/docker-compose down

Way around 2: Use the groups hack

This is docker specific, but theoretically you could design your API in the same way

Create a unix group called docker and add your user to it.

# create the group
sudo groupadd docker
# add the current user to it
sudo usermod -aG docker $USER
# Log in and out to ensure this works

Thus, even though the docker daemon runs as root, it makes this socket read/writable by the docker group, allowing non-root users to communicate with docker without sudo. Nifty, huh?

Resources