How do I deploy code with Git?
Basic methods
The simplest way: on your server, clone the repo and run `git pull` to update. You can automate this with a post-receive hook on a bare Git repo, or a webhook from GitHub/GitLab that triggers a script. For example, a webhook can call a URL that runs `git pull && systemctl restart myapp`.
More robust: use a CI/CD tool (Jenkins, GitHub Actions, GitLab CI) that checks out the code, builds it, and deploys the artifact to your server. This avoids giving the server direct Git access and keeps builds reproducible.
- Push to a central repo (GitHub, GitLab, Bitbucket).
- Trigger deployment via webhook, CI pipeline, or manual pull.
- On the server, fetch the new code and restart the service.
- Use tags or branches to control what gets deployed (e.g., `main` for production).
Best practices
Don't deploy directly from a developer's laptop. Use a central repo and a consistent process. Tag releases (e.g., `v1.2.3`) so you can deploy a specific version and roll back easily.
Keep secrets out of Git. Use environment variables or a secrets manager. For deployment, consider using `git archive` to export a clean copy without the `.git` directory, or build a package (Docker image, tarball) in CI and deploy that instead of pulling Git on the server.
Common mistakes
- Running `git pull` on a production server with uncommitted local changes, causing merge conflicts.
- Storing database passwords or API keys in the Git repository.
- Deploying from a feature branch instead of a tested release branch or tag.
