Reputation: 6086
I'm new to Nginx, which I'm running in a Docker container to serve a simple website. I want to add an /health
endpoint that simply returns status 200 + some arbitrary content.
I copied and adjusted the standard nginx.conf
from /etc/nginx/
by adding
server {
location /health {
return 200 "alive";
}
}
at the bottom inside the http
block. But when I run the Docker, and try to access localhost/health
, I just get no such file or directory
. Accessing the website at localhost
works fine.
I also tried copying other code blocks, e.g., this one: https://gist.github.com/dhrrgn/8650077
But then I get conflicting server name "" on 0.0.0.0:80, ignored nginx: [warn] conflicting server name "" on 0.0.0.0:80, ignored
.
Am I placing the location
at a wrong location inside nginx.conf
? Do I need some special server configuration? What's the problem?
Upvotes: 7
Views: 18732
Reputation: 1337
In case you want to do it in one line without building an image, you can just do the following:
#1 Create Nginx.conf file
nano /tmp/nginx-tester/nginx.conf
and put the following content there:
events {}
http {
server {
location / {
root /usr/share/nginx/html;
}
location /health {
return 200 '{"status":"UP"}';
add_header Content-Type application/json;
}
}
}
If you see, all what it's doing is to serve a http status 200 with a json stating the status is UP
#2 Run the NgInx Image
Just to have it in one line, and avoid keep recreating the image each time, you can just specify a volume like this:
docker run -it --rm -d -p 8077:80 --name nginx-tester -v /tmp/nginx-tester/nginx.conf:/etc/nginx/nginx.conf:ro nginx
-it
: interactive processes (like a shell)--rm
: the container is removed when it exits-p 8077:80
: hostPort:containerPort--name
: Name of the Container-v
: Bind mount a volume (fileHost:fileContainer:ReadOnly)nginx
: Image that will be downloaded and ran#3 Test it
You can do it just by going to the server
:8077
(Which was the port you specified at the step #2
)
~ > curl http://myserver:8077/health
{"status":"UP"}
👆This way you can change the config file, and by just doing a:
docker restart nginx-tester
You are able to reload the file without the need of rebuilding the image.
Upvotes: 0
Reputation: 6086
The problem was with my Nginx Docker setup/configuration: I am using nginx:alpine
, which has the configuration files at /etc/nginx/conf.d/
. There, default.conf
defines the default configuration of Nginx. So, I had to remove default.conf
and copy my configuration there instead. In the Dockerfile
:
COPY nginx.conf /etc/nginx/conf.d/nginx.conf
RUN rm /etc/nginx/conf.d/default.conf
Of course, I also had to define the standard route in nginx.conf
then:
server {
location / {
root /usr/share/nginx/html;
}
location /health {
return 200 'alive';
add_header Content-Type text/plain;
}
}
Upvotes: 9