Docker in Docker setup with VSCode Dev Containers: How to access running docker containers on the host machine

Viewed 2977

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?

1 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.

    FROM docker:19.03.12-dind-rootless@sha256:7606255ca83a7f516fae1b78299b79774f1f798ba9fc792a7231e7b0967ddb05
    USER root

    # Change this with your dependencies, note that this uses alpine apk
    RUN apk add git bash curl make vim go

    USER rootless
    ENV DOCKER_HOST=unix:///var/run/user/1000/docker.sock
Related