Docker镜像推送后本地挂载卷无法在其他设备持久化问题求助
Hey there, let's break down what's going on here and how to fix it.
Why this happens
The core issue here is that Docker volumes are a runtime-only feature—they don't get included in your Docker image. When you use volumes: - ./:/var/www in your docker-compose.yml, you're just mounting your local machine's code directory into the container while it runs. This doesn't add your application files to the myblog image you built and pushed to the registry. So when you pull that image on another computer, the /var/www directory in the image is empty (since your Dockerfile only sets the working directory but doesn't copy in your code).
Solution 1: Package your app code directly into the Docker image
This way, your application code lives inside the image itself—so when you pull it on another machine, everything is ready to go. Here's how to adjust your setup:
- Update your Dockerfile to copy your application code into the image. Add these lines right before the
WORKDIR /var/wwwline (or after creating the system user):# Copy all application code into the image COPY . /var/www # Fix file permissions to match your web user USER root RUN chown -R $user:$user /var/www USER $user - Adjust your docker-compose.yml for production (or when you want to use the packaged image):
- You can comment out or remove the
volumes: - ./:/var/wwwline under theappservice. This tells the container to use the code that's already inside the image instead of mounting a local directory. - For local development, you can keep the volume mount to retain hot-reloading functionality. Consider using separate compose files (like
docker-compose.dev.ymlanddocker-compose.prod.yml) to switch between environments easily.
- You can comment out or remove the
Solution 2: Replicate your local directory setup on the target machine
If you want to keep using volume mounts (for example, if you need to edit code on the other machine), you just need to mirror your local setup:
- Clone your application repository (or copy all your code files) into a directory on the target machine.
- Make sure the docker-compose.yml on that machine has the same
volumes: - ./:/var/wwwline for theappservice. - Don't forget to copy over supporting files like
.env,.docker/nginx/conf.d/, and.docker/mysql/—these are needed for your services to run correctly.
Quick note on use cases
- For development, volume mounts are great because they let you edit code without rebuilding the image every time.
- For production, packaging code into the image is generally better—it ensures consistency across deployments and avoids dependency on local files.
内容的提问来源于stack exchange,提问作者tom1337

