无法将本地项目推送到AWS搭建的Git仓库:执行git push production master时提示Permission denied (publickey)
Hey there, let's walk through fixing this public key permission issue step by step—this is super common when setting up Git on EC2, so don't stress!
1. Fix your local .pem file permissions first
SSH is strict about key file permissions—if other users on your machine can read the key, it'll refuse to use it. Run this on your local machine, replacing /path/to/your-key.pem with the actual path to your EC2 key:
chmod 600 /path/to/your-key.pem
If you get a "Permission denied" error here, prepend sudo to the command.
2. Make Git use your .pem key for the connection
By default, Git might not automatically pick up your EC2 .pem key. You have two options:
One-time quick fix
Add the key to your push command directly:
GIT_SSH_COMMAND="ssh -i /path/to/your-key.pem" git push production master
Permanent fix (recommended)
Set up an SSH config so you don't have to specify the key every time:
- Open your SSH config file (create it if it doesn't exist):
nano ~/.ssh/config - Add this block, replacing placeholders with your details:
Host ec2-git-repo HostName 35.154.37.131 User root IdentityFile /path/to/your-key.pem - Save and exit (Ctrl+O, hit Enter, then Ctrl+X in nano).
- Update your Git remote to use this host nickname:
git remote remove production git remote add production ssh://ec2-git-repo/var/repo/site.git
Now you can run git push production master normally.
3. Verify permissions on the EC2 Git repository
First, SSH into your EC2 instance to check the repo setup:
ssh -i /path/to/your-key.pem root@35.154.37.131
Once logged in:
- Check if the repo directory is owned by
root:
If not, fix ownership:ls -ld /var/repo/site.gitchown -R root:root /var/repo/site.git - Ensure it's a bare repository (you can't push to a repo with a working directory):
cd /var/repo/site.git git config --bool core.bare true
4. Check EC2 Security Group settings
Head to your AWS Console → EC2 Dashboard → find your instance → check its attached security group. Make sure there's an inbound rule allowing SSH (port 22) from your local IP address (you can temporarily use 0.0.0.0/0 for testing, but lock it down to your IP afterward for security).
5. Confirm root login is allowed on EC2
Some EC2 AMIs disable root login by default. While logged into your instance:
- Open the SSH config file:
nano /etc/ssh/sshd_config - Look for
PermitRootLogin—it should be set toyesorprohibit-password(which allows key-based login, just not password login). - If you changed it, restart the SSH service:
# For Amazon Linux 2, Ubuntu 18.04+ (systemd) systemctl restart sshd # For older systems service sshd restart
Test first before pushing
Before trying Git push again, test if you can SSH into the EC2 instance successfully:
ssh -i /path/to/your-key.pem root@35.154.37.131
If this works, your Git push should too!
内容的提问来源于stack exchange,提问作者suraj singh

