简体   繁体   中英

Docker: mounting a volume overwrites container

I'm trying to write a Dockerfile for use as a standardized development environment.

Dockerfile:

FROM node:9.5.0

WORKDIR /home/project

# install some stuff...

# clone the repo
RUN git clone https://github.com/... . 

# expose 
VOLUME /home/project

# fetch latest changes from git, install them and fire up a shell.
CMD git pull && npm install && /bin/bash

After building the image (say with tag dev ), Running docker run -it dev gives me a shell with the project installed and up-to-date.

Of course changes I make in the container are ephemeral so I want to mount /home/project on the host OS, I go to an empty directory project on the host and run:

docker run -it -v ${pwd}:/home/project dev

But my project folder gets overwritten and is empty inside the container.

How can mount the volume such that the container writes to the host folder and not the opposite?


OS: Windows 10 Pro.

When you mount a volume, read/write are both bi-directional by default. That means that anything you write in the container will show up in the host directory and vice versa.

But something weird is happening in your case, right?

In your build process, you are cloning a git repository. During the build process, the volume does not get mounted. The git data resides in your docker image.

Now, when you are running the docker container, you are mounting the volume. The mount path in your container will be synced with your source path. That means the container directory will be overwritten with the contents of the host directory. That's why your git data has been lost.

Possible Solution:

Run a script as CMD. That script can clone the git repo, among other things.

run.sh

#!/bin/bash

# clone the repo
RUN git clone https://github.com/... . 

Dockerfile

RUN ADD run.sh /bin

# run run.sh, install them and fire up a shell.
CMD run.sh && npm install && /bin/bash

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM