Docker入门教程3:Docker Compose连接被拒绝问题求助
Hey there, let's work through why you're hitting that curl: (7) Failed to connect to localhost port 80: Connection refused error after deploying your stack. Here are the key checks to run step by step:
1. Confirm Swarm Mode is Active
Even if your docker stack deploy command ran without obvious errors, Docker Swarm isn't enabled by default on a fresh Ubuntu 16.04 install. First verify its status:
docker info | grep Swarm
If the output shows Swarm: inactive, initialize Swarm with this command, then redeploy your stack:
docker swarm init
2. Double-Check Your Port Mapping in the YAML File
From Docker's tutorial part 2, your Flask app listens on port 5000 inside the container. Make sure your .yml file maps the host's port 80 to this container port—your ports section should look like:
ports: - "80:5000"
If you only have - "5000" (no host port specified), the service won't be reachable on localhost:80. Fix the YAML, update your stack with docker stack deploy -c <your-file.yml> <stack-name>, then test again.
3. Verify Your Service Tasks Are Running
Grab the full service name from your docker service ls output, then check the status of individual tasks:
docker service ps <full-service-name>
Look at the STATE column—if tasks are in Err or Restarting state, the container isn't starting properly. Pull the service logs to debug the root cause:
docker service logs <full-service-name>
Common issues here include missing Python dependencies, incorrect image references, or permission errors inside the container.
4. Check Ubuntu's Firewall Settings
Ubuntu 16.04 uses ufw by default, which might block incoming traffic on port 80. First check if ufw is active:
sudo ufw status
If it's enabled, temporarily disable it to test if that's the block:
sudo ufw disable
If curl works after this, add a permanent rule to allow port 80 traffic:
sudo ufw allow 80/tcp sudo ufw enable
5. Inspect the Service's Endpoint Configuration
Confirm the service is actually binding to the host's port 80 with this command:
docker service inspect --format '{{.Endpoint.Ports}}' <full-service-name>
You should see output like [map[Protocol:TCP PublishPort:80 TargetPort:5000]]. If the PublishPort is missing or set to a different number, your port mapping is misconfigured.
内容的提问来源于stack exchange,提问作者Kurobara

