Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng serve not working in Docker container

I have this Docker Compose configuration where I simply create a NodeJS container and install Angular CLI inside.

After a docker-compose up -d, I'm able to SSH inside the container with docker-compose run node bash. ng new works perfectly but ng serve does not seem to work. It's launched correctly, no error in the console. But, if I visit localhost (ad I mapped port 4200 to 80), nothing loads.

Am I missing something?

like image 741
Axiol Avatar asked Oct 16 '17 20:10

Axiol


1 Answers

In your Dockerfile you are missing the Expose line such as:

EXPOSE 4200

Try placing it before your last RUN command in the docker file.

This line exposes the port in the container itself (4200 in this case) so the mapping from compose works (80:4200).

Compose just does this: forward 80 from the host to 4200 in the container. But it doesn't know or care if the 4200 is actually being listened to. The Expose in the dockerfile makes sure when the image is built, to expose this port for the future running containers, so your ng serve can listen to it.


Resolution

So to get what you want with docker-compose run, use publish to publish the ports. As run doesn't use the mappings from your docker-compose.yml, it ignores them. So use it like this:

docker-compose run --publish 80:4200 node bash

Then create the angular app and start it up as you were doing.


Test Example For Future Reference

cd tmp (or any writable folder)

ng new myProject

cd myProject

ng serve --host 0.0.0.0 (--host 0.0.0.0 to listen to all the interfaces from the container)

Then in your browser, go to localhost and you should see the angular welcome page now as the port 4200 is published and bound to the host port 80 through the publish command as I showed above.

Everytime you have port forwarding issues, if you open a new terminal keeping the other terminal where you executed the original run command and run docker ps you will see this in the Ports column:

0.0.0.0:80->4200/tcp which means that your host on port 80 is forwarding to your container in port 4200 successfully.

If you see something like 4200/tcp and not the -> part, that means there is no mappings or ports published.

like image 172
Juan Avatar answered Oct 03 '22 17:10

Juan