Angular and Docker
I recently started experimenting with Docker containers for code deployment. I have to say, it’s pretty fun and easy to use. I like that the Windows GUI program is as easy if not easier to use than the command interface, but I’ve been using both as I learn.
The docker tutorials I’ve found use React for the frontend, so they didn’t cover the biggest gotcha for running Angular apps in a Docker container: the defaults for ng serve. By default, the ng serve command will set your host as localhost (127.0.0.0). This works great for both local development and server deployments. So, you put together a Dockerfile with your normal startup commands, spin up a local docker container with your ports mapped to 4200:4200, and go to http://localhost:4200 and get … nothing. Which makes sense, the code is running inside a container and your command is coming from outside the container. Your code is sitting there, waiting for someone local to talk to it instead of listening for signals from the outside.
The key to getting around this is to set the –host flag on ng serve like so:
ng serve --host 0.0.0.0
However, we can’t just run this as a CMD in a Dockerfile. If you’re running your docker container from a basic node container (FROM node
), that container won’t recognize your Angular command out of the box. So we need one more step in our Dockerfile to add @angular/cli:
RUN npm install
RUN npm install -g @angular/cli
You can specify your angular/cli version to whatever version your app uses, which I would recommend. My project is currently running Angular 8, so that last line looks like:
RUN npm install -g @angular/cli@8.0.0
Then you can end your Dockerfile with the command
CMD ng serve --host 0.0.0.0
Et voilĂ ! Now when you run the local container and fire up the old browser, the site loads as expected.