如何将Spring Boot RESTful Web Service Docker镜像部署到EC2?
Alright, let's walk through getting your Spring Boot container up and running on EC2 so it's publicly accessible. You've already checked off the hard parts—now let's tie it all together:
Step 1: Launch & Configure Your EC2 Instance
- Start by spinning up an EC2 instance (a t2.micro is perfect for starters since it’s free tier eligible). Pick an AMI that supports Docker—Amazon Linux 2 or Ubuntu are both solid choices.
- Critical security group setup: Add an inbound rule allowing traffic on port 8080 (or your app’s port) from
0.0.0.0/0(you can restrict to your IP first for testing, then open it up). Don’t forget to allow SSH traffic too, so you can connect to the instance later.
Step 2: Connect to Your EC2 Instance
- Use SSH to log into your instance. For Amazon Linux 2, the default user is
ec2-user; for Ubuntu it’subuntu. Your command will look like this:ssh -i "your-key-pair.pem" ec2-user@your-ec2-public-ip
Step 3: Install Docker on EC2
For Amazon Linux 2:
sudo yum update -y sudo amazon-linux-extras install docker -y sudo service docker start sudo usermod -aG docker ec2-user
Log out and back in to apply the group permissions change.
For Ubuntu:
sudo apt update -y sudo apt install docker.io -y sudo systemctl start docker sudo systemctl enable docker sudo usermod -aG docker ubuntu
Same here—log out and back in after running these commands.
Step 4: Pull Your Docker Image from Docker Hub
- Run this command to fetch your image (replace with your actual Docker Hub username, image name, and tag):
docker pull your-dockerhub-username/your-image-name:tag
Step 5: Run the Container & Map Ports
- Start your container in detached mode, mapping the container’s 8080 port to the EC2 instance’s 8080 port:
Thedocker run -d -p 8080:8080 your-dockerhub-username/your-image-name:tag-dflag ensures the container runs in the background so you can keep using your terminal.
Step 6: Test Public Access
- Grab your EC2 instance’s public IP (or public DNS) and test your endpoint with curl or a browser:
You should see that familiar static JSON you tested locally—success!curl http://your-ec2-public-ip:8080/your-api-endpoint
Quick Troubleshooting Tips
- If you can’t reach the endpoint, double-check your security group rules—make sure port 8080 is open to the public.
- Verify the container is running with
docker ps. If it’s not, check the logs withdocker logs <container-id>to debug startup issues. - Confirm your Spring Boot app is configured to listen on
0.0.0.0(not justlocalhost)—this lets it accept connections from outside the container. Most default Spring Boot setups do this, but it’s worth checking your application properties if you run into issues.
内容的提问来源于stack exchange,提问作者KasparTr
相关产品推荐
相关产品推荐

