如何从GitHub拉取Docker镜像并在EC2实例中构建镜像?
Hey there! Let's break down exactly how to pull a Docker image hosted on GitHub. First, a quick heads-up: GitHub stores container images in their GitHub Container Registry (GHCR)—so that's the registry we'll be interacting with here. Here's your step-by-step guide tailored for your EC2 instance:
Step 1: Confirm Docker is installed on your EC2 instance
First, check if Docker is up and running with this command:docker --versionIf it's not installed, use your EC2's package manager to set it up:
- For Amazon Linux:
sudo yum install docker -y - For Ubuntu:
sudo apt install docker.io -y
Don't forget to start and enable the Docker service so it runs on boot:
sudo systemctl start docker sudo systemctl enable docker- For Amazon Linux:
Step 2: Find your image's GHCR path
GitHub container images follow this standard format:ghcr.io/<your-github-username>/<image-repo-name>:<tag>For example, if your GitHub username is
krish0033and your image repo ismy-web-apptaggedlatest, the full path would beghcr.io/krish0033/my-web-app:latest. You can grab this path by visiting your GitHub repo's Packages tab (look in the repo sidebar under "Packages") or checking the repo's README if the image is documented there.Step 3: Log into GHCR (only for private images)
If the image is private, you'll need to authenticate with a GitHub Personal Access Token (PAT). First, create a PAT in your GitHub account settings with theread:packagespermission (this is the only permission needed for pulling private images). Then run this command on your EC2 instance to log in securely:echo "<your-github-pat>" | docker login ghcr.io -u <your-github-username> --password-stdinUsing
--password-stdinkeeps your PAT out of your shell history, which is way safer than typing it directly.Step 4: Pull the image
Now run the pull command with your image's full GHCR path:docker pull ghcr.io/<your-github-username>/<image-repo-name>:<tag>If you're pulling the
latesttag, you can skip the:latestpart—Docker will default to it automatically:docker pull ghcr.io/<your-github-username>/<image-repo-name>Step 5: Verify the pull worked
Check your local Docker images to confirm the image is now on your EC2 instance:docker imagesYou should see your GitHub-hosted image listed in the output.
Quick Tips
- Public images: No login required! Just run the
docker pullcommand directly. - PAT security: On EC2, avoid hardcoding your PAT in scripts. Store it in AWS Secrets Manager and retrieve it programmatically, or use a temporary environment variable that doesn't get saved.
内容的提问来源于stack exchange,提问作者krish0033

