Docker for development: make local files visible to a container with volume mapping

I wrote a very simple right-to-the-point Docker introduction post if you’re new to Docker.

If you want to see your code changes applied right away to a running Docker container, you need to make sure to run the container using the share volumes tag: -v (or --volume).

The -v tag expects as a parameter the host path, followed by colon (:), followed by the destination path inside the container:

-v /home/projects/my-app:/src

The parameter above will bind your local /home/projects/my-app directory to the container’s /src directory. That means that all changes you make to the files under /home/projects/my-app will be accessible in the container’s /src folder, allowing you to execute or inspect the code there in /src.

You use the -v tag when you first run the container:

$ docker run -v /home/projects/my-app:/src -it ubuntu bash

The line above starts a container running ubuntu, giving you access to the command line (the -it and the bash parts) and binds your local path /home/projects/my-app to the container’s /src

That’s very useful but you might run into a problem where after starting the container, you try to make changes to the code in your text editor and when trying to save the changes, there’s a permission error message.

This post explains why this happens in great detail but the gist of it is that Docker runs the container as root so all its files belongs to root and your user in your local host is not the same user (even if your user has root privileges!). So when you try to save the changes locally, the container goes “whoa, whoa, whoa, watcha doin’ there?”

Here’s how to fix the volume sharing permission in docker: you tell Docker to run the container as the host’s current user. To accomplish this use the -u or --user tag:

--user $(id -u):$(id -g)

There are a few things happening here. This parameter is telling the user tag to:

  1. get the current user’s UID  (user ID) id -u
  2. wrapped in a shell resolver $()
  3. tell the container :
  4. to get the current user’s GUID (group ID) id -g
  5. wrapped in a shell resolver $()

The end result is that now the Docker container will run as the current host user and will therefore have the same permissions inside and outside the container. Voilà!

Reference:

Docker run official docs

The post Docker for development: make local files visible to a container with volume mapping was originally published at flaviabastos.ca