This article mainly focus on how to run a HTTP server inside a docer container. The key point is port mapping.
I skipped installation of docker at ubuntu here. Please refer to my last docker note.
For server example, I have some in my github.
Here I choose Rust version for example.
Run Rust docker
# pull rust official image to local docker pull rust # run a container docker run -itd -p 8080:5000 --name httpserver rust
-itd means ‘interactive’, ‘TTY’ and ‘detached’, which are running options of container.
-p set the port mapping. 8080 is our server port, 5000 is the container port.
So we need set the server in side container to listen http request at port 5000.
Because we run the container in detached mode, first we need attach to the container (go into it).
# httpserver is our container name docker attach httpserver
Inside container we can use
ctrl-q to detach again.
Another way to go into the container is open another bash.
# -it has same meaning as 'docker run' docker exec -it httpserver bash
Since we have one more bash now, it’s OK to close one bash.
Now assume we are already in the container. Vim and Git might be needed. But I skip their installation here.
To fetch and run the server:
# clone source code from my github git clone https://github.com/ysmiles/ServerClientExamples-Rust # compile and run cd tcptime/ cargo run
It might be necessary to change line 11 for
src folder from ‘TcpListener::bind(“127.0.0.1:8000”)’ to ‘TcpListener::bind(“0.0.0.0:5000”)’ before compiling.
Because we want this server works from ‘outside’ view, and before we mapped some port to container port 5000.
Now detach from the container and test at server local to see the result.
# curl can give a http request to a specific address curl http://0.0.0.0:8080
The output should be something like below:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Hello!</title> </head> <body> <h1>Hello!</h1> <p>Hi from Rust</p> <p>Current server time is:</p> <p>2017-12-06 11:20:17</p> </body> </html>
Then test remotely. Here is my page, you can test it. This http serve will return the server machine local time.