Skip to content

Instantly share code, notes, and snippets.

@cebe
Last active January 25, 2023 09:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cebe/30ea219b3adfde781174fa9bd1823fdb to your computer and use it in GitHub Desktop.
Save cebe/30ea219b3adfde781174fa9bd1823fdb to your computer and use it in GitHub Desktop.
How to run docker commands as your local user, not root
version: '2'
services:
web:
image: yiisoftware/yii2-php:7.4-apache
#!/bin/bash
#
# Same as the Makefile, but as a bash script, see Makefile for detailed explanation.
#
CONTAINER_NAME=web
echo "preparing bash environment..."
docker-compose exec $CONTAINER_NAME bash -c "grep '^$(whoami):' /etc/passwd >/dev/null || useradd -m '$(whoami)' --uid=$(id -u) -G www-data -s /bin/bash"
docker-compose exec $CONTAINER_NAME bash -c "sed -i 's/#force_color_prompt=yes/force_color_prompt=yes/' /home/$(whoami)/.bashrc"
echo -e "\nYou are now in the \033[1m$CONTAINER_NAME\033[0m container.\n"
docker-compose exec --user=$(id -u) $CONTAINER_NAME bash
# This is a Makefile that implements helpers for a docker stack
#
# This example shows how to run a bash in a docker-compose container as your local user,
# so files are created owned by that user instead of root.
#
# For this to work, the user inside the container must have the same ID as the user outside.
# The name does not matter much but to avoid confusion it is helpful to make them have the same user name.
# You get a users ID by running the `id -u` command, and the users name is `whoami`.
#
# How it works:
# line 22: create a user with the same name and ID inside the docker container if it does not exists.
# The user is also added to the www-data group to work well with files created by the webserver, you may want to change this if you have a different use case.
# line 23: enable colored prompt in bash (optional)
# line 25: run a bash with the same user ID
#
CONTAINER_NAME=web
cli: bash
bash:
@echo "preparing bash environment..."
docker-compose exec $(CONTAINER_NAME) bash -c "grep '^$(shell whoami):' /etc/passwd || useradd -m '$(shell whoami)' --uid=$(shell id -u) -G www-data -s /bin/bash"
docker-compose exec $(CONTAINER_NAME) bash -c "sed -i 's/#force_color_prompt=yes/force_color_prompt=yes/' /home/$(shell whoami)/.bashrc"
@echo "\nYou are now in the \033[1m$(CONTAINER_NAME)\033[0m container.\n"
@docker-compose exec --user=$$(id -u) $(CONTAINER_NAME) bash
@SOHELAHMED7
Copy link

Typo

- name and ID inside the docker conterainer if it does not exists
+ name and ID inside the docker container if it does not exists 

@cebe
Copy link
Author

cebe commented Jan 25, 2023

fixed, thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment