Search code examples
dockerdockerfiledocker-volumedocker-in-docker

Cannot connect to the Docker daemon without -v /var/run/docker.sock:/var/run/docker.sock


I am trying to run docker inside docker container and container have nodeJs App.

Here is my Dockerfile:

FROM docker:dind   
WORKDIR /app  
RUN apk add --update nodejs nodejs-npm  
COPY . /app  
RUN npm install  
CMD node app.js  
EXPOSE 4000

I built docker image (newdockerimage) using above Dockerfile and creating container using docker run -d --privileged -v /var/run/docker.sock:/var/run/docker.sock -v /var/lib/docker:/var/lib/docker newdockerimage.

I am able to install docker inside container but all the docker images which are on host system is also sharing inside container because of volume (/var/run/docker.sock).

If I dont use volume -v /var/run/docker.sock:/var/run/docker.sock while running container, I am getting below error:- Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? Because container will be node app (since that is entrypoint),so overriding docker:dind entrypoint

Please help me ! How can I run docker inside container without sharing volume (without copying docker images of host system)


Solution

  • When you override the default CMD of Docker-dind by node app.js then it will not start Docker service. so as a result you will get

    Cannot connect to the Docker daemon
    

    Because docker is not running in your container.

    So the workaround is to start docker in the background and your node application in foreground.

    FROM docker:dind   
    WORKDIR /app  
    RUN apk add --update nodejs nodejs-npm  
    COPY app.js /app  
    RUN npm install express
    CMD nohup dockerd &> output & sleep 1 && node app.js  
    EXPOSE 4000
    

    Build the image and start the container like

    docker run -it --privileged --name test --rm my-docker-dind
    

    enter image description here