keepcalculator

06 Numbers and Powers

Git Auto-Deploy on a VPS: Step-by-Step

Card No. 06·81680 · Updated · Standard formula, shown below

This guide walks you through setting up automatic deployment with Git on a VPS (Virtual Private Server). You’ll push code to a central Git repository on the server, and a hook will automatically update your live website files. This eliminates manual FTP uploads and ensures your production environment matches your repository.

What You’ll Need

  • A VPS running Linux (Ubuntu/Debian recommended) with SSH access.
  • Git installed on the server (check with git --version; install via sudo apt install git if missing).
  • Your project code in a Git repository (local or remote like GitHub/GitLab).
  • Basic familiarity with the command line and SSH.
  • Web server (Apache/Nginx) and a web root directory (e.g., /var/www/html).

Step-by-Step

  1. Prepare the server directories. Create a bare Git repository to act as the central point. Bare repositories have no working tree; they only store history. Run:
    sudo mkdir -p /var/repo/site.git
    sudo chown -R $USER:$USER /var/repo/site.git
    cd /var/repo/site.git
    git init --bare
  2. Set up the live web directory. Ensure your web root exists and is writable by the user that runs the deployment hook. For example:
    sudo mkdir -p /var/www/html
    sudo chown -R $USER:$USER /var/www/html
  3. Create a post-receive hook. Inside the bare repo, navigate to hooks and create a file named post-receive:
    cd /var/repo/site.git/hooks
    nano post-receive

    Paste the following script (adjust paths to match your setup):

    #!/bin/bash
    TARGET="/var/www/html"
    GIT_DIR="/var/repo/site.git"
    BRANCH="main"
    
    while read oldrev newrev ref
    do
        if [[ "$ref" = "refs/heads/$BRANCH" ]]; then
            echo "Deploying branch $BRANCH to $TARGET"
            git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $BRANCH
            # Optional: run build commands here, e.g., npm install, composer install
        else
            echo "Skipping deployment for branch $ref"
        fi
    done

    Save and close. Make it executable:

    chmod +x post-receive
  4. Configure the local repository. On your development machine, add the server as a remote:
    git remote add production user@your-server-ip:/var/repo/site.git

    Replace user with your SSH username and your-server-ip with the server’s IP or domain.

  5. Push to deploy. Push your main branch to the production remote:
    git push production main

    The post-receive hook will run automatically and update the web root. You should see “Deploying branch main to /var/www/html” in the output.

  6. Test the deployment. Create a simple test file in your local repo, commit, and push again. Check that the file appears in the web root on the server. If you have a domain pointed to the server, visit it in a browser.

Common Mistakes

  • Wrong branch name: The hook checks for a specific branch (e.g., main). If your local branch is master, update the BRANCH variable accordingly.
  • Permissions issues: The user running the hook may not have write access to the web root. Ensure the target directory is owned by the same user or use sudo carefully inside the hook (but prefer proper ownership).
  • Forgetting to make the hook executable: If the hook doesn’t run, check ls -l post-receive; it must have -rwxr-xr-x permissions.
  • Using a non-bare repository on the server: If you cloned your repo directly on the server, the hook approach won’t work correctly. Always use a bare repo for receiving pushes.
  • Ignoring build steps: If your project requires compilation (e.g., React, Sass), the hook must run those commands. Otherwise, the live site will show outdated or broken assets.

Tips

  • Use a dedicated user: Create a system user like gitdeploy with limited permissions to run deployments, reducing security risks.
  • Keep secrets out of the repo: Use environment variables or a .env file that is not tracked, and symlink it into the web root.
  • Log everything: Redirect output from the hook to a log file for debugging: echo "Deploying..." >> /var/log/deploy.log
  • Use SSH keys: Set up SSH key authentication for passwordless pushes, which is more secure and convenient.
  • Test on a staging server: Set up a similar hook on a staging VPS to catch issues before production.

Troubleshooting

Hook doesn’t run: Check the file permissions and that the shebang #!/bin/bash is correct. Test the hook manually by executing bash post-receive from the hooks directory.

Push succeeds but files don’t update: Verify the branch name in the hook matches the branch you’re pushing. Also check that the target directory path is correct and writable.

Permission denied when pushing: Ensure the user has SSH access and the remote URL is correct. Test with ssh user@server to confirm.

Deployment works but site shows errors: Check file ownership and permissions. If your web server runs as www-data, you may need to change ownership: sudo chown -R www-data:www-data /var/www/html.

Build commands fail in hook: The hook runs in a minimal environment; you may need to set the PATH or use absolute paths to executables (e.g., /usr/bin/npm).

Frequently Asked Questions

Can I deploy multiple branches to different directories?

Yes, modify the hook to read the branch name and choose the target directory accordingly. For example, deploy staging to /var/www/staging and main to /var/www/production.

What if I use a remote repository like GitHub?

You can either push to your VPS directly as shown, or use GitHub Actions to SSH into the server and run deployment commands. The hook method works with any Git client.

How do I handle database migrations?

Add migration commands to the hook, but ensure they are idempotent (safe to run multiple times). Better yet, use a separate migration tool and trigger it manually or via a CI/CD pipeline.

Is it safe to use git checkout -f in production?

It can overwrite local changes on the server. If you have uploaded files (like user uploads) that are not in the repo, exclude them from the web root or use a different deployment strategy (e.g., rsync).

Can I rollback to a previous version?

Yes, simply push an older commit to the production branch. The hook will check out that commit. For a more robust rollback, tag releases and push the tag.

Do I need to install Git on the server?

Yes, the server must have Git to receive pushes and run the hook. Most VPS images come with Git pre-installed, but you can install it with sudo apt install git.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →