'Connect to a Nest.js server inside a docker container
I'm trying to create a container for a Nest.js server. For now,I only have the basic version of the server that creates automatically when you create a Nest project. I tried some things in Dockerfile and docker-compose, but when I start the container and go to browser to localhost:3042 it says the page isn't working, but it should GET an object.
So right now, my Dockerfile looks like this:
FROM node:10
WORKDIR /microservices
COPY package*.json ./
COPY tsconfig.json tsconfig.json
COPY src src
RUN ["npm","install","global","@nestjs/cli"]
RUN ["npm", "install"]
EXPOSE 3042
ENTRYPOINT ["npm","run","start"]
And my docker-compose.yaml looks like this:
version: "3.2"
services:
server:
container_name: server
hostname: localhost
build: ./
ports:
- "3042:3042"
I run docker-compose up, go to browser and it doesn't work.
The output of the docker-compose up command is:
server | [Nest] 18 - 07/12/2019, 1:44 PM [NestFactory] Starting Nest application...
server | [Nest] 18 - 07/12/2019, 1:44 PM [InstanceLoader] AppModule dependencies initialized +26ms
server | [Nest] 18 - 07/12/2019, 1:44 PM [RoutesResolver] AppController {/}: +10ms
server | [Nest] 18 - 07/12/2019, 1:44 PM [RouterExplorer] Mapped {/, GET} route +7ms
server | [Nest] 18 - 07/12/2019, 1:44 PM [NestApplication] Nest application successfully started +5ms
So it seems like inside something is going on and the app starts successfully.
I looked on some examples, the one from their documentation where python is used and another example with Express.js, but didn't help me.
Solution 1:[1]
Nest is using the port 3000 by default, so I think that's the problem. You can try to change it in the main.ts:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3042);
}
or changing your docker configuration. Dockerfile
EXPOSE 3000/tcp
docker-compose.yml
version: "3.2"
services:
server:
container_name: server
hostname: localhost
build: ./
ports:
- 3000:3000
Solution 2:[2]
If anyone is having the same issue, my problem was that I added a second argument in app.listen
change it from this:
await app.listen(this.port, this.host);
to this
await app.listen(this.port);
solved my issue
Solution 3:[3]
In my case, I was using FastifyAdapter, and it so happens that when being inside docker, you have to specify the host as "0.0.0.0" instead of localhost. The thing is, you have to add the host as a second parameter, instead of concatenate the strings:
WRONG
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
await app.listen("0.0.0.0:3000");
CORRECT
const app = await NestFactory.create(AppModule);
await app.listen(3000, "0.0.0.0");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Amiral Jion |
| Solution 3 | Javi Marzán |
