Sterling Mcleod
Sterling Mcleod

Reputation: 1

Docker development workflow with mounted volume?

What are common practices for saving changes made on a container onto my local file system when using a Docker development image?

My first thought is to create a link between a local directory and the container's workspace directory so that any change I make in the container's workspace will automatically be saved in a local directory. However, if I run something like this:

sudo docker run -v ./workspace_persist:/path/to/workspace/on/container repo:tag

Then it erases everything in the container's workspace because my local directory is empty.

Do you:

  1. Copy the container's workspace to the local directory during the container's startup? If so, then how?
  2. Make the mount point in the container separate from the workspace, and then manually copy the workspace over to the mount point in the container before exiting? If so, then what mechanisms do you put in place to make sure you don't forget before exiting?
  3. Something else?

If it matters - this is for a C++ project.

What I tried:

  1. Tried to mount a volume linking a local directory with the container's workspace

sudo docker run -v ./workspace_persist:/path/to/workspace/on/container repo:tag

I expected the local directory to get populated with the container workspace's contents. However, the opposite happened - it made the container workspace's contents equal to my local directory contents on startup.

  1. Read through the Bind mounts page. I did not see an answer to my question, or I did not understand it well enough to see the answer.

Upvotes: 0

Views: 102

Answers (1)

Yu Wei Liu
Yu Wei Liu

Reputation: 809

I'll do it this way:

Folder structure

- project
|- src
 |- main.cpp
|- Dockerfile
|- docker-compose.yml

Dockerfile

FROM gcc:14.1.0

RUN apt-get update && apt-get -y install cmake libprotobuf-dev protobuf-compiler

WORKDIR /workspace

COPY . .

docker-compose.yml

version: '1'
services:
  cworkspace:
    container_name: cworkspace
    tty: true
    stdin_open: true
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - .:/workspace

Under the ./project folder, run

# Build image and start up the container
$ docker compose up --build -d

# Unless changing the `Dockerfile`, the next time start up the container using
# Don't worry. There is no any command here will erase your local files or directory
$ docker compose up -d

Attach to the container:

$ docker exec -it cworkspace /bin/bash

# You will see
root@add399b8e525:/workspace# ls
Dockerfile  docker-compose.yml  src
root@add399b8e525:/workspace#

Whenever you do any change under /workspace, it will also modify things in your local directory, i.e. /project.

After setting up the environment, you could open/close container as you wish:

$ docker compose up -d
$ docker compose down

Upvotes: 0

Related Questions