在运行容器内使用Dockerfile执行docker build重建镜像
Hey there! Let's break down exactly what you need to do to rebuild your Docker image with the updated Dockerfile—since you're new to Docker, I'll keep each step clear and actionable.
Step 1: Copy the updated Dockerfile from your running container to your host machine
First off, Docker builds images from files on your host (or a build context), not directly from files inside a running container. So we need to pull that updated Dockerfile out of your my-container first.
- If you don't know exactly where the Dockerfile lives inside the container, run this to hop into the container and locate it:
docker exec -it my-container bash # Once inside, search for the Dockerfile (example command): find / -name Dockerfile # Let's say you find it at /app/Dockerfile—note that path, then exit the container exit - Copy the Dockerfile to your host's current working directory:
Replacedocker cp my-container:/app/Dockerfile .//app/Dockerfilewith the actual path you found in the container.
Step 2: Build and tag your new Docker image
Now that the updated Dockerfile is on your host, you can use docker build to create the new image, and the -t flag to add a tag (so you can easily reference it later).
Run this command in the same directory where you copied the Dockerfile:
docker build -t my-image:latest .
-t my-image:latestsets the image name tomy-imageand tag tolatest(you can change this to something likemy-image:v2if you want versioned tags).- The
.at the end tells Docker to use the current directory as the build context (it looks for the Dockerfile here by default).
If your Dockerfile has a different name or is in another directory, add the -f flag to specify it:
docker build -t my-image:latest -f ./path/to/your-updated-Dockerfile .
Step 3: (Optional) Restart your container with the new image
If you want to run a new container using your fresh image, you'll need to stop and remove the old one first (skip this if you just need the image for later use):
# Stop the running container docker stop my-container # Remove the old container (this won't affect your new image) docker rm my-container # Start a new container with your updated image docker run -d --name my-container my-image:latest
Add any extra flags you need to the docker run command (like port mappings or volume mounts) that you used for the original container.
Quick tips for beginners
- Use a
.dockerignorefile in your build context directory to exclude files/folders that don't need to be included in the build (like logs, node_modules, or local configs)—this keeps your image smaller and builds faster. - Tags are super useful for tracking versions: instead of always using
latest, try tags likev1.0,v1.1so you can roll back if needed. - Make sure any files referenced in your Dockerfile (like scripts or dependencies) are also copied from the container to your build context—Docker can't access files inside the container during the build process.
内容的提问来源于stack exchange,提问作者Ruairios

