如何为通过docker run启动的运行中容器挂载卷(含AWS EC2场景)
Hey there! Let's walk through how to add a volume mount to your running example container. Since you're on Docker 19.03.12, we have two solid approaches depending on whether you need the mount to persist across container restarts or just need a temporary fix.
Option 1: Persistent Mount (Survives Container Restarts)
This is the recommended approach for most use cases, especially production environments. Older Docker versions like 19.03 don’t let you add permanent mounts to running containers directly, so we’ll recreate the container with the mount included.
Follow these steps:
- Stop the running container:
docker stop example - Remove the container (your image stays safe—we’ll rebuild it with the mount):
docker rm example - Recreate the container with your desired volume mount
Use your original startup command, adding either the-v(short form) or--mount(long, more explicit form) flag to define the mount. For example, to bind-mount the host directory/home/ubuntu/app-datato/app/datainside the container (read-write):# Using -v flag (simple, widely used) docker run --name example -p 8080:80 -dt -v /home/ubuntu/app-data:/app/data example-image:latest # OR using --mount (more verbose, clearer for complex setups) docker run --name example -p 8080:80 -dt --mount type=bind,source=/home/ubuntu/app-data,target=/app/data example-image:latest- If you prefer a Docker-managed volume (Docker handles storage location and backups), replace the host path with a volume name (Docker creates it automatically if missing):
docker run --name example -p 8080:80 -dt -v my-docker-volume:/app/data example-image:latest
- If you prefer a Docker-managed volume (Docker handles storage location and backups), replace the host path with a volume name (Docker creates it automatically if missing):
Option 2: Temporary Mount (Does NOT Survive Restarts)
If you need a quick, temporary mount without restarting the container (great for testing or debugging), use the nsenter tool to access the container's mount namespace:
- Get the container's PID:
PID=$(docker inspect -f '{{.State.Pid}}' example) - Create the target directory inside the container (if it doesn’t exist):
docker exec example mkdir -p /app/data - Mount the host directory to the container (requires root privileges):
This mount will disappear as soon as the container stops or restarts.sudo nsenter --target $PID --mount --uts --ipc --net --pid mount /home/ubuntu/app-data /app/data
Important Notes
- Permissions: Make sure the host directory has the correct permissions for the user running inside the container. Adjust permissions on the host with
chown/chmod, or specify a user in thedocker runcommand with--user. - Docker-managed vs Bind Mounts: Docker-managed volumes are easier to manage (built-in backup tools, consistent storage paths), while bind mounts give you direct control over the host filesystem.
内容的提问来源于stack exchange,提问作者saikrishna

