dockerrestgogorillamux

Mux Router doesn't work in Dockerized golang project


I tested locally and it works totally fine on my local. I can get responses from POST, GET methods.

But when I dockerize the application and try to test the same endpoints, I get nothing. I have tried all the suggestions herein Stackoverflow. So I will paste my Dockerfile and Makefile to get your opinions on it.

My Dockerfile:

FROM golang:1.16.5 AS build-env

RUN set -x \
    && apt-get update -y \
    && apt-get install -y locales \
                          make \
                          xz-utils \
                          zip \
    && rm -rf /var/lib/apt/lists/*

FROM build-env AS builder
WORKDIR /build
COPY . .
RUN set -x \
    && make

FROM debian:buster AS runner

RUN set -x \
    && apt-get update -y \
    && apt-get install -y ca-certificates \
    && rm -rf /var/lib/apt/lists/* \
    && update-ca-certificates

COPY --from=builder /build/bin/* .
CMD ["./applicaitonx"]

and my Makefile:

build:
    go build -o bin/applicaitonx -v -buildmode=exe .

to be able to build the docker, I'm using the following command;

docker build -t app .

and then I run it.

I see that the application is running and listenandserve doesn't throw an error at all. BUT mux is not routing at all. It says it listens but it doesn't. I will also copy the following part in main.go

srv := &http.Server{
    Handler: router,
    Addr: ":" + os.Getenv("PORT"),
}

if err := srv.ListenAndServe(); err != nil {
    log.Fatal("ListenAndServe: ", err)
}

I inspect all the env variables, so os.GetEnv("PORT") doesn't return null. I'm sure about it. I wrote some debug comments, and as far as I see codes doesn't go even that debug comments. So it doesn't print anything at all.


Solution

  • It might be possible that the port you are using inside the container is not exposed to outside world, hence you can't reach them. Try adding -p flag like below:

    docker run -p P1:P2
    

    P1 = TCP port

    P2 = Container port

    Please refer: this doc