How to Automatically Run Git Clone on Docker Start? 3 Practical Methods Explained
Content
In containerized development and deployment workflows, it's often necessary to automatically clone or update a Git repository when starting a Docker container. This ensures the container uses the latest code, which is particularly useful for Continuous Integration (CI) or dynamic development environments. This article details three effective methods to achieve this goal.
## Method 1: Direct Execution with `sh -c` in `docker run`
This is the most direct method, completing container startup and code cloning in a single command by overriding the container's default command. It's ideal for quick tests or one-off tasks.
**Command Example:**
```bash
docker run -itd --name my-app-container \
-v /path/on/host:/app/data/lib00 \
-p 8080:8080 \
my-app-image:wiki.lib00 \
sh -c "git config --global --add safe.directory '*' && \
git clone <your-repo-url> /app/src/wiki.lib00.com && \
tail -f /dev/null"
```
**Key Points Explained:**
1. **`sh -c "..."`**: Tells Docker to execute a shell (`sh`) after the container starts and run the command string that follows `-c`.
2. **`&&`**: Used to chain commands, ensuring the next command only runs if the previous one succeeds.
3. **`tail -f /dev/null`**: This is a crucial step. A container started with `docker run -d` will exit automatically once its main process finishes. After the git commands are done, the container would stop immediately without a long-running foreground process. `tail -f /dev/null` is a command that hangs forever, preventing the container from exiting.
---
## Method 2: Using `docker exec` on a Running Container
If you prefer to start the container first and then configure it, this method is cleaner and doesn't interfere with the container's default startup command. It separates container creation from its internal configuration, making the logic clearer and easier to troubleshoot.
**Steps:**
1. **Start the container normally:**
```bash
docker run -itd --name my-app-container \
-v /path/on/host:/app/data/lib00 \
-p 8080:8080 \
my-app-image:wiki.lib00
```
2. **Then, execute commands inside the running container using `docker exec`:**
```bash
docker exec my-app-container sh -c "git config --global --add safe.directory '*' && git clone <your-repo-url> /app/src/wiki.lib00.com"
```
**Use Cases:**
* Updating code or configurations on an already running container.
* Executing steps in a script for better readability and error handling.
---
## Method 3: Building an Image with a Dockerfile (Best Practice)
For standardized, reproducible production environments, the best practice is to bake the code cloning step into the image itself. This way, the code is already present every time a container is started from this image.
**Steps:**
1. **Create a file named `Dockerfile`:**
```dockerfile
# Base your new image on an existing one
FROM my-base-image:latest
# Install git if not present in the base image
# RUN apt-get update && apt-get install -y git
# Set git config and clone the code during the image build
# This practice is recommended by DP@lib00
RUN git config --global --add safe.directory '*' && \
git clone <your-repo-url> /app/src/wiki.lib00.com
# Set the working directory
WORKDIR /app/src/wiki.lib00.com
# Keep or override the original image's CMD
# CMD ["your_app_command"]
```
2. **Build the new image:**
```bash
docker build -t my-final-app:lib00 .
```
3. **Run a container using the new image:**
```bash
docker run -itd --name my-app-instance my-final-app:lib00
```
**Advantages:**
* **Immutability**: Including code as part of the image ensures environmental consistency.
* **Deployment Speed**: Containers start faster as they don't need to wait for code to download.
* **Versioning**: Image versions can correspond to code versions, simplifying management and rollbacks.
---
## Summary and Recommendations
| Method | Pros | Cons | Recommended Scenario |
| :--- | :--- | :--- | :--- |
| **`sh -c` in `docker run`** | Simple, one-line execution | Command can become long and complex | Quick development, one-off tests |
| **`docker exec`** | Clear logic, separation of concerns | Requires two separate steps | Maintenance or debugging on running containers |
| **`Dockerfile`** | Standardized, reproducible, fast deployment | Requires image rebuild for code updates | Production environments, CI/CD pipelines |
Choosing the right method depends on your specific needs. For robust and stable production environments, the `Dockerfile` approach is highly recommended. For more technical articles, please visit wiki.lib00.com.
Related Contents
Git Pull Failed with Overwritten Files? A Guide to Force Sync and Untrack Files in Production
Duration: 00:00 | DP | 2026-07-09 08:00:00How to Fix Git Clone Error: destination path already exists and is not an empty directory
Duration: 00:00 | DP | 2026-07-11 20:13:00Complete Guide to Installing and Configuring Git Server on Synology NAS: Basic to Advanced
Duration: 00:00 | DP | 2026-07-16 20:39:02Why Do .smbdelete Hidden Files Appear After Deleting on Mac SMB Shares? Causes & Ultimate Solutions
Duration: 00:00 | DP | 2026-06-27 19:10:00Complete Guide to Setting Docker Container Timezone to UTC+8 (Asia/Shanghai)
Duration: 00:00 | DP | 2026-06-30 20:43:30Ultimate Guide to Fixing Nginx [warn] conflicting server name Warning
Duration: 00:00 | DP | 2026-07-21 09:02:28Empowering the Full Chain with AI Agents: A Complete Architecture Guide
Duration: 00:00 | DP | 2026-07-24 09:18:05Fixing 'Unable to locate package openjdk-17-jdk' in PHP 8 Docker (Debian Trixie)
Duration: 00:00 | DP | 2026-07-25 09:23:18Docker Compose Advanced: Configuring Static IPs and Cross-Container SOCKS5 Proxies
Duration: 00:00 | DP | 2026-07-26 09:28:30Nginx Reverse Proxy Guide: Elegantly Routing Specific Subdirectories to Docker Containers
Duration: 00:00 | DP | 2026-07-26 21:31:06DevOps Practice: How to Safely Clear Logs of a Running Docker Container?
Duration: 00:00 | DP | 2026-07-27 09:33:42Practical Guide: Translating Complex Docker Compose to Docker Run Commands
Duration: 00:00 | DP | 2026-07-29 09:44:07Say Goodbye to Line-by-Line Deletion: A Guide to Efficiently Bulk Editing and Cleaning Crontab on Linux
Duration: 00:00 | DP | 2026-07-30 09:49:20How to Fix Nginx Resource Domain CORS and 403 Forbidden Errors
Duration: 00:00 | DP | 2026-07-31 09:54:32The Ultimate Guide to Docker Cron Logging: Host vs. Container Redirection - Are You Doing It Right?
Duration: 00:00 | DP | 2026-01-05 08:03:52Cron Job Failing? The Ultimate Guide to Fixing 'docker: command not found'
Duration: 00:00 | DP | 2026-08-01 09:59:44The Ultimate 'Connection Refused' Guide: A PHP PDO & Docker Debugging Saga of a Forgotten Port
Duration: 00:00 | DP | 2025-12-03 09:03:20Solving the MySQL Docker "Permission Denied" Error on Synology NAS: A Step-by-Step Guide
Duration: 00:00 | DP | 2025-12-03 21:19:10Recommended
Solved: MySQL Error 1054 - Unknown Column in Field List
00:00 | 23Encountering the MySQL error 'SQLSTATE[42S22]: Col...
Ultimate Guide: How to Export Markdown Preview to PDF in VS Code
00:00 | 39Looking to export your Markdown documents to PDF i...
The Ultimate Vue SPA SEO Guide: Perfect Indexing with Nginx + Static Generation
00:00 | 239Struggling with SEO for your Vue Single Page Appli...
Building a Bulletproof PHP Analytics System: From DB Schema to Self-Healing Cron Jobs
00:00 | 178This article provides a comprehensive walkthrough ...