如何在运行时将项目源码添加至Docker容器?
Hey there! Since you need to add your project source code at runtime (instead of build time) while keeping that complex build process inside the container, here are a couple of practical approaches tailored to your setup:
1. Use Docker Bind Mounts (Most Direct Approach)
This method maps your local source code directory directly into the container at runtime, letting your existing build script process the fresh code each time the container starts.
Step 1: Adjust Your Dockerfile
Remove the COPY line that adds your source code during build, and update the startup command to run your build script before starting Apache. Here's the revised Dockerfile:
FROM base-image RUN mkdir -p /proj/branches/www RUN mkdir -p /proj/branches/mybranch # Ensure the mount target exists RUN chown root:www-data -R /proj COPY config-and-build.sh . EXPOSE 80 # Run build script first, then start Apache CMD ["/bin/sh", "-c", "/config-and-build.sh && apachectl -D FOREGROUND"]
Step 2: Run the Container with Mounted Source
Use the -v flag to bind your local source directory to the container's /proj/branches/mybranch path:
docker run -v /path/to/your/local/proj/branches/mybranch:/proj/branches/mybranch -p 80:80 your-built-image
Key Notes:
- Permissions: If your local directory has different user/group permissions than the container, add a
chownstep insideconfig-and-build.shto fix access issues (or run the container withdocker run -u $(id -u):$(id -g) ...to match your local user). - Build Consistency: Since the build runs on container startup, make sure all build dependencies are already installed in your
base-image(they should be, since you previously ran the build in the container).
2. Use Named Volumes (For Persistent/Cached Builds)
If you want to keep a persistent copy of your source code in a Docker-managed volume (instead of binding directly to your local filesystem), use a named volume:
Create the Volume First
docker volume create my-project-source
Copy Your Source Code to the Volume
docker run --rm -v my-project-source:/proj/branches/mybranch -v /path/to/your/local/proj/branches/mybranch:/local-src busybox cp -r /local-src/. /proj/branches/mybranch/
Run the Container with the Named Volume
docker run -v my-project-source:/proj/branches/mybranch -p 80:80 your-built-image
This is useful if you need to share the source code across multiple containers or want Docker to handle storage management.
Quick Debug Tip
To verify your source code is mounted correctly before running the full build, start an interactive shell in the container:
docker run -it -v /path/to/your/local/proj/branches/mybranch:/proj/branches/mybranch your-built-image /bin/bash
Then check if /proj/branches/mybranch contains your files with ls -la.
内容的提问来源于stack exchange,提问作者zunbeltz

