Skip to content

Instantly share code, notes, and snippets.

@gwpl
Last active July 12, 2024 10:07
Show Gist options
  • Save gwpl/92207935c22080490f311254cd6c8f33 to your computer and use it in GitHub Desktop.
Save gwpl/92207935c22080490f311254cd6c8f33 to your computer and use it in GitHub Desktop.
Puzzle: 127.0.0.1:1234 works, but localhost:1234 does not

Puzzle : why 127.0.0.1:1234 works and localhost:1234 does not?

https://x.com/GWierzowiecki/status/1811703703683907651

PUZZLE (I just debugged it! I didn't know what's going on)

  • You run server, that is e.g. PHP attached inside docker to 0.0.0.0:6942 and ports exposed are 6942:6942
HOST_PORT=6942
CONTAINER_PORT=6942
    docker run -d --rm --name $CONTAINER_NAME -p $HOST_PORT:$CONTAINER_PORT $IMAGE_NAME

$  grep localhost /etc/hosts
127.0.0.1       localhost
::1     localhost
$ grep 6942 Dockerfile 
# Expose port 6942
EXPOSE 6942
CMD ["php", "-S", "0.0.0.0:6942", "-t", "/app"]

And when you ask in browser or CURL: via 127.0.0.1:6942 WORKs, but via localhost:6492 DOES NOT work!

$ curl http://127.0.0.1:6942
{"message":"Test Service","version":"1.0.0","status":"running"}$ 
$ curl http://localhost:6942
curl: (56) Recv failure: Connection reset by peer

What is the problem?

Solution: https://gist.github.com/gwpl/7c5a32ffaacb891f5df6e962fd4b3900

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment