So I have a Go application that I am deploying to a EC2 instance with Ansible and Jenkins pipeline as a Docker image. I have an image that I can access from outside the host using the IP address and the port number, 8080, using Postman. When I deploy a new image I cannot get a response using the ip address and port number. When I ssh into the server I can reach the endpoint using localhost and the port number. If I stop that image and start the first I can then reach it again.
What are the possible differences between these images that makes it so the endpoint can no longer be accessed via the ip address?
My Docker Compose File:
version: '2'
services:
project-1:
image: ...
volumes:
- /var/log:/var/log
network_mode: host
environment:
- ...
cpu_shares: 1236
mem_limit: 2619m
My DockerFile:
FROM golang:1.10
WORKDIR /go/src/...
COPY . .
RUN go get -d -v ./...
RUN go install -v ./...
EXPOSE 8080-8080
CMD ./run.sh
I have also attempted removing network_mode from Docker Compose file and replacing it with ports as shown below with no success:
ports:
- "0.0.0.0:8080:8080"
Make sure the container binds the port to the host port. In the container networking documentation you can read the following:
By default, when you create a container, it does not publish any of its ports to the outside world. To make a port available to services outside of Docker, or to Docker containers which are not connected to the container’s network, use the --publish or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host. Here are some examples.
You can try running your container with the -p
flag explained above:
docker run -p 0.0.0.0:8080:80 your-container-image
We have discovered the answer. This problem happened after adding the following go code:
serv := &http.Server{
Addr: "localhost" + port,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
Handler: router,
}
This sets timeouts for responses. We found that the word "localhost" was not mapping to the ip address of the host. Changing it to the following fixed the issue:
serv := &http.Server{
Addr: "0.0.0.0" + port,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
Handler: router,
}
I can now access the server from outside the host.