Showing posts with label Nginx. Show all posts
Showing posts with label Nginx. Show all posts

Tuesday, October 8, 2024

Use nginx running in Docker container to serve php sites running on the host

In one of my previous articles I showed how to use nginx running in Docker container to serve .Net sites running on Kestrel web server on the host. In the current article I will show how to do similar thing with php sites.

So idea is the same: we have nginx running in Docker container and number of php sites running on the host and want containerized nginx to serve these sites. For example we will use Mantis (popular bug tracker) and Wordpress (popular CMS engine based on php) sites. For simplicity we will use assumption that MySQL databases used by php sites are running on the same host.

On the host php sites are served by php fpm daemon (php FastCGI process manager) which may listen for IP:port or unix sockets. One option is to use this php fpm from the host, however e.g. in case of unix sockets it will require tricky rights setups. Also since we anyway eager to move to containers it will be preferable to create lightweight php fpm container which will serve our php sites from the host. First of all we need to create Docker image based on php fpm with MySQL extension installed (so php will be able to connect to MySQL db). It can be created with the following Dockerilfe:

FROM php:7.4-fpm
RUN docker-php-ext-install mysqli pdo_mysql

On the first line we tell Docker that our image should be based on php fpm v7.4 and on the 2nd line we install MySQL extension for php so it will be able to connect to the database. Note that by default php fpm containers listen port 9000 - it will be used when we will configure nginx.conf file for our site.

Then build the image and push it to our Docker images registry:

docker build -t {php-image-tag}
docker push {php-image-tag}

On the next step we need to setup nginx and php containers with the following docker compose file:

name: myservice
services:
  nginx:
    image: nginx:latest
volumes:
- /var/www/myphpsite:/var/www/myphpsite ports: - 80:80 restart: always networks: - mynetwork extra_hosts: - host.docker.internal:host-gateway
php:
image: {php-image-tag}
volumes:
- /var/www/myphpsite:/var/www/myphpsite
restart: unless-stopped
networks:
- mynetwork
extra_hosts:
- host.docker.internal:host-gateway

Important line here is where we add a volume which points to the folder with php scripts (/var/www/myphpsite) both to nginx and php. With this line nginx container will be able to serve also static files (css, images, js, etc) from our php site and at the same time php container will have access to php scripts. Also it is important that nginx and php containers are located in the same network (mynetwork) (in this case containers will be able to communicate using containers names) and that we added host.docker.internal extra host (so php fpm container will be able to connect to the database running on the host).

Next step is to setup nginx.conf for our php site:

server {
    listen 80;
    server_name example.com;
    root /var/www/myphpsite;
    ...
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass myservice-php-1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    }
}

Here with root directive we specify that php sources are located in /var/www/myphpsite folder (remember that we added this folder to php and nginx containers volumes) and configure php fpm to process php scripts. Directive fastcgi_pass instructs nginx to execute a CGI script (php in our case) using the FastCGI protocol (which is different from proxy_pass directive used for .Net sites running on Kestrel - which sends an HTTP request to another web server). Since both containers are located in the same network we may use container name (myservice-php-1) and port number (9000) for fastcgi_pass directive.

And last but not least - since php scripts will be processed inside container we need to change host in database connection string from localhost to host.docker.internal (we can do that because added extra_host to our containers in docker compose files). Location where it is stored depends on php site. E.g. for Mantis it is stored in /.../{site_folder}/config/config_inc.php in $g_hostname variable, for Wordpress-based sites in /var/www/{site_folder}/wp-config.php in DB_HOST variable. After that your php sites will work under nginx running in Docker container.

Wednesday, September 18, 2024

Use nginx running in Docker container to serve .NET sites running on Kestrel both in host and Docker containers

In one of my previous articles I made brief introduction to Docker – containerization technology which gives more control over infrastructure. Suppose that we have number of .NET sites running on Kestrel in Linux and published via nginx to the internet like shown on the following schema (ports numbers are only for example here):

And we want to move all our infrastructure to Docker (backend, database, nginx itself, etc) so it will look like this:

On practice however this switch will take time and at some time period we will have both sites running still in the Linux host and sites running in Docker containers, and we will need to serve both types:

Since only one app may listen to 80 port we need to decide whether we want to keep nginx service running on the host or move nginx to Docker and configure it to serve both sites from the host and sites from Docker containers. In this article I will describe this last option.

Since nginx is running in Docker there won’t be many problems with hosting sites running also in Docker. Just run these sites and nginx container in the same network:

#docker-compose-nginx.yml
name: myservice
services:
  nginx:
    image: nginx:latest
    ports:
      - 80:80
    …
    networks:
      - mynetwork

and nginx will be able to resolve containers by names. I.e. if site’s container name is mysite-web-1 you may specify nginx.conf like this:

server {
	listen 80;
	listen [::]:80;
	server_name mysite.ru www. mysite.ru;
	location / {
		proxy_pass http://mysite-web-1:80;
		…
	}
}

However with sites running in host it is not that straightforward. Since nginx is running in Docker container which has own IP address we need to instruct it to which IP it should forward requests if they came for sites running on the host.

We can do that by adding special extra host host.docker.internal to nginx docker compose:

name: myservice
services:
  nginx:
    image: nginx:latest
    ports:
      - 80:80
    restart: always
    networks:
      - mynetwork
    extra_hosts:
      - host.docker.internal:host-gateway

If we will check /etc/hosts file inside nginx container we will see that host.docker.internal points to 172.17.0.1 IP address which is default IP used by Docker for host:

docker exec -it myservice-nginx-1 sh
more /etc/hosts
…
host.docker.internal 172.17.0.1

Next step is to instruct nginx to forward request to the host if it came for site running there. For doing that we need to modify nginx.conf and specify host.docker.internal with appropriate port in proxy_pass property:

server {
	listen 80;
	listen [::]:80;
	server_name mysite.ru www.mysite.ru;
    	location / {
		proxy_pass http://host.docker.internal:5000;
		…
    	}
}

However that is still not enough. If your .NET site is running on Kestrel you most probably configured to run it as a daemon via the following commands:

systemctl enable mysite.ru.service
systemctl start mysite.ru.service

where mysite.ru.service file contains the following line:

Environment=ASPNETCORE_URLS=http://localhost:5000

With our current configuration if we will open shell inside our nginx container and try to reach our site via curl we will get Connection refused:

docker exec -it myservice-nginx-1 sh
curl -X GET http://host.docker.internal:5000
Connection refused

The problem here is that Kestrel is currently listening only for localhost IP (127.0.0.1). We can check it on the host using the following command:

netstat -tulpn | grep 5000
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      22496/dotnet
tcp6       0      0 ::1:5000                :::*                    LISTEN      22496/dotnet

but request from nginx container goes to 172.17.0.1. To solve that we need to modify /etc/systemd/system/mysite.ru.service and add http://172.17.0.1:5000 to ASPNETCORE_URLS after semicolon:

Environment=ASPNETCORE_URLS=http://localhost:5000;http://172.17.0.1:5000

and reload the service:

systemctl stop mysite.ru.service
systemctl daemon-reload
systemctl start mysite.ru.service
systemctl status mysite.ru.service

After that check that it listen 5000 port also on 172.17.0.1:

netstat -tulpn | grep 5000
tcp        0      0 172.17.0.1:5000         0.0.0.0:*               LISTEN      22496/dotnet
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      22496/dotnet
tcp6       0      0 ::1:5000  

And now if we go inside container shell and try to reach the site connection should be successful:

docker exec -it myservice-nginx-1 sh
curl -X GET http://host.docker.internal:5000
Connection successful

which means that nginx is now able to serve sites running both in containers and on the host itself.

Tuesday, August 27, 2024

Nginx uses 1st available server configuration when domain name not resolved

If you host several sites on nginx (which means that you also have several domain names pointing to your server's IP address) then you may face with the following issue. Suppose that we have 3 domain names pointing to our server's IP with running nginx:

example1.com
example2.com
example3.com

Sites example1.com and example2.com are configured in nginx, but there is no example3.com. The problem is that by default nginx will still proxy example3.com to 1st available server config (depending in which order they are defined in nginx.conf file, let's say example1.com in our example) which may be quite confusing because we requested example3.com but see content of example1.com in browser window (in browser address bar we will still see example3.com).

In order to avoid this behavior we need to add default server configuration to nginx.conf which will return 404 like that:

server {
	listen 80 default_server;
	server_name  _;
	return 404;
}

Now if we will try to open example3.com we will see 404 page returned by nginx:

which is more clear and expected behavior from my point of view.

Monday, June 19, 2017

Problem with Sharepoint NTLM authentication and nginx proxy

Some time ago we faced with the following problem: on-premise Sharepoint 2013 site has 2 authentication zones: Default and Custom. Default authentication zone uses NTLM authentication while Custom uses FBA. Both zones have own host headers (e.g. windows.example.com for Default zone and fba.example.com for Custom). Both host headers were specified in Alternate access mappings of appropriate web application in Sharepoint central administration.

For accessing Sharepoint site remotely nginx was used as reverse proxy between client and internal Sharepoint farm. With this configuration FBA url worked both from within Sharepoint farm (from RDP session) and remotely while Windows url worked only from Sharepoint server and only if we bypass nginx by specifying windows.example.com in hosts file and pointing it to 127.0.0.1 (self IP address). All attempts to login through nginx failed with 401 Unauthorized (and I mean login using custom host header. Logins from RDP session via serve’s name worked).

Investigation showed that nginx doesn’t works well with NTLM authentication (see e.g. How to enable windows authentication through a reverse proxy), so at the end we got rid from nginx in between and configured access to Sharepoint via IP table. If you have solution which works with nginx please share it. Anyway I hope that this information will be helpful.