I am using VSCode dev containers as a golang development environment using the default golang image. I added the following snippet to the Dockerfile
to download the Docker CLI:
# Add Docker
RUN apt-get update
&& apt-get -y install --no-install-recommends
apt-transport-https
ca-certificates
curl
gnupg2
software-properties-common
&& curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -
&& add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"
&& apt-get update
&& apt-get -y install --no-install-recommends docker-ce
# Clean up
&& apt-get autoremove -y
&& apt-get clean -y
&& rm -rf /var/lib/apt/lists/*
# Symlink docker socket
RUN ln -s "/var/run/docker-host.sock" "/var/run/docker.sock"
And added the following mount to the mounts in the devcontainer.json
:
"mounts": ["source=/var/run/docker.sock,target=/var/run/docker-host.sock,type=bind"]
This does allow me to access the Docker Daemon running on my local machine. However if I spin up a postgres container:
docker run -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password -p 5432:5432 -d postgres:9
I can connect to it from my local machine but not from inside the Dev Container. Is there any way to specify the networking option when spinning up a Dev Container (e.g. allow host networking or create a shared network)? Or is there another way I can connect to another running docker container from inside my Dev Container?
3
Answers
This answer is only good if you are able to run the other container within your Dev Container.
You can setup your Dev Container with docker-in-docker. This way you can run docker containers within your Dev Container (and thus the networking will work). The Dockerfile would look like this. There’s a medium article that explains this well.
Assuming I understood you problem correctly, you want to:
Assuming a default setup, both your devcontainer container and your Postgres container should live in the same network. If they do, the devcontainer can communicate with Postgres using the Postgres container’s
IP:port
. You can usedocker inspect
command to find that out.If you prefer to remain in the docker-from-docker approach, different from the alternative solution called docker-in-docker proposed by wanheda, you can connect the dev container to your host ports.
Assuming that you preserve your host’s docker socket mount:
you can add this line to your .devcontainer/devcontainer.json file:
In this way, you give the dev container a way to reach your host’s address by just using the host name host.docker.internal
I suggest you to read this article, because docker-from-docker has the advantage of lower overhead but it has also some bind mounting limitations.
Use Docker or Kubernetes from a container