With above simple Dockerfile, I should access the website via port 8000 on my host. But it is not. After check the issue, I think the problem is in package.json:
"start": "http-server -a localhost -p 8000 -c-1",
So it starts on port 8000 on localhost.
If I change this line to
"start": "http-server -p 8000 -c-1",
I can access the application from my mac.
So may I know how to mapper the localhost:port in container to outside?
It isn’t really possible to map the container’s localhost to the outside. The process in the container must bind to the container’s eth0. It looks like that is what you accomplished by removing the -a localhost from that command.
A workaround might be to run another process in the container that listens on the container’s eth0 and proxies for you, but that isn’t really a solution in my book.
Well, the first problem you will have to get over is how you’re going to launch a second process alongside your main process. What will you do if that secondary process stops running? You are using onbuild, so you’ll probably have to add a bunch more stuff after the ONBUILD bit, and add supervisord or some other process babysitter. That makes it difficult to take advantage of the CMD bits from the ONBUILD portion of the build.
Assuming you can work out all that, you have several choices. There are purpose built userspace proxies out in the wild. It’s been a few years, but I have seen some fancy work done with bash and socat.
Your better bet will likely be to have your process listen directly on the container’s eth0 rather than trudge through all of that.