11.1. Lesson: Instalar o Servidor QGIS¶
O objetivo desta lição: Para aprender a instalar o Servidor QGIS no Debian Stretch. Com pequenas variações, você também pode segui-lo para qualquer distribuição baseada no Debian como o Ubuntu e seus derivados.
Nota
No Ubuntu, você pode usar seu usuário comum, acrescentando sudo
aos comandos que requerem permissões de administrador. No Debian você pode trabalhar como administrador (root
), sem usar sudo
.
11.1.1.
Follow Along: Install from packages¶
Nesta lição, faremos apenas a instalação dos pacotes, como mostrado aqui.
Instale o Servidor QGIS com:
apt install qgis-server
# if you want to install server plugins, also:
apt install python-qgis
O Servidor QGIS deve ser usado na produção sem o QGIS Desktop (com o Servidor X que acompanha) instalado na mesma máquina.
11.1.2.
Follow Along: Servidor QGIS Executável¶
O executável do Servidor QGIS é qgis_mapserv.fcgi
. Você pode verificar onde foi instalado executando find / -name 'qgis_mapserv.fcgi'', que deve gerar algo como ``/usr/lib/cgi-bin/qgis_mapserv.fcgi
.
Opcionalmente, se você quiser fazer um teste de linha de comando no momento, poderá executar o comando /usr/lib/cgi-bin/qgis_mapserv.fcgi
, que deve gerar algo como:
QFSFileEngine::open: No file name specified
Warning 1: Unable to find driver ECW to unload from GDAL_SKIP environment variable.
Warning 1: Unable to find driver ECW to unload from GDAL_SKIP environment variable.
Warning 1: Unable to find driver JP2ECW to unload from GDAL_SKIP environment variable.
Warning 1: Unable to find driver ECW to unload from GDAL_SKIP environment variable.
Warning 1: Unable to find driver JP2ECW to unload from GDAL_SKIP environment variable.
Content-Length: 206
Content-Type: text/xml; charset=utf-8
<ServiceExceptionReport version="1.3.0" xmlns="https://www.opengis.net/ogc">
<ServiceException code="Service configuration error">Service unknown or unsupported</ServiceException>
</ServiceExceptionReport>
Isso é bom, pois ele diz que estamos no caminho certo, pois o servidor está dizendo que não solicitamos um serviço suportado. Veremos mais adiante como fazer solicitações WMS.
11.1.3. Follow Along: Configuração do servidor HTTP¶
Para acessar no Servidor QGIS instalado a partir de um navegador da Internet, precisamos usar um servidor HTTP.
Nesta lição, usaremos o Servidor HTTP Apache, chamado coloquialmente de Apache.
Primeiro, precisamos instalar o Apache executando o seguinte comando em um terminal:
apt install apache2 libapache2-mod-fcgid
Você pode executar o Servidor QGIS no site padrão ou configurar um host virtual especificamente para isso, da seguinte maneira.
No diretório /etc/apache2/sites-available
, vamos criar um arquivo chamado qgis.demo.conf
, com este conteúdo:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName qgis.demo
DocumentRoot /var/www/html
# Apache logs (different than QGIS Server log)
ErrorLog ${APACHE_LOG_DIR}/qgis.demo.error.log
CustomLog ${APACHE_LOG_DIR}/qgis.demo.access.log combined
# Longer timeout for WPS... default = 40
FcgidIOTimeout 120
FcgidInitialEnv LC_ALL "en_US.UTF-8"
FcgidInitialEnv PYTHONIOENCODING UTF-8
FcgidInitialEnv LANG "en_US.UTF-8"
# QGIS log (different from apache logs) see https://docs.qgis.org/testing/en/docs/user_manual/working_with_ogc/ogc_server_support.html#qgis-server-logging
FcgidInitialEnv QGIS_SERVER_LOG_FILE /var/log/qgis/qgisserver.log
FcgidInitialEnv QGIS_SERVER_LOG_LEVEL 0
FcgidInitialEnv QGIS_DEBUG 1
# default QGIS project
SetEnv QGIS_PROJECT_FILE /home/qgis/projects/world.qgs
# QGIS_AUTH_DB_DIR_PATH must lead to a directory writeable by the Server's FCGI process user
FcgidInitialEnv QGIS_AUTH_DB_DIR_PATH "/home/qgis/qgisserverdb/"
FcgidInitialEnv QGIS_AUTH_PASSWORD_FILE "/home/qgis/qgisserverdb/qgis-auth.db"
# See https://docs.qgis.org/testing/en/docs/user_manual/working_with_vector/supported_data.html#pg-service-file
SetEnv PGSERVICEFILE /home/qgis/.pg_service.conf
FcgidInitialEnv PGPASSFILE "/home/qgis/.pgpass"
# Tell QGIS Server instances to use a specific display number
FcgidInitialEnv DISPLAY ":99"
# if qgis-server is installed from packages in debian based distros this is usually /usr/lib/cgi-bin/
# run "locate qgis_mapserv.fcgi" if you don't know where qgis_mapserv.fcgi is
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin/">
AllowOverride None
Options +ExecCGI -MultiViews -SymLinksIfOwnerMatch
Order allow,deny
Allow from all
Require all granted
</Directory>
<IfModule mod_fcgid.c>
FcgidMaxRequestLen 26214400
FcgidConnectTimeout 60
</IfModule>
</VirtualHost>
Você pode fazer o acima em um sistema Linux desktop colando e salvando a configuração acima depois de fazer nano/etc/apache2/sites-available/qgis.demo.conf
.
Nota
Veja que algumas das opções de configuração são explicadas na seção Servidor Configuração avançada.
Vamos agora criar os diretórios que armazenarão os logs do Servidor QGIS e o banco de dados de autenticação:
mkdir /var/log/qgis/
chown www-data:www-data /var/log/qgis
mkdir /home/qgis/qgisserverdb
chown www-data:www-data /home/qgis/qgisserverdb
Nota
www-data
é o usuário do Apache em sistemas baseados no Debian e precisamos que o Apache tenha acesso a esses locais ou arquivos. O comando chown www-data ...
altera o proprietário dos respectivos diretórios e arquivos para www-data
.
Agora podemos ativar o host virtual, ativar o mod fcgid
se ainda não estiver ativado e reiniciar o serviço apache2
:
a2enmod fcgid
a2ensite qgis.demo
systemctl restart apache2
Nota
Se você instalou o Servidor QGIS sem executar um Servidor X (incluído no Linux Desktop) e também deseja usar o comando GetPrint
, instale um Servidor X falso e peça ao Servidor QGIS para usá-lo. Você pode fazer isso executando os seguintes comandos.
Instalar xvfb:
apt install xvfb
Crie o arquivo de serviço:
sh -c \
"echo \
'[Unit]
Description=X Virtual Frame Buffer Service
After=network.target
[Service]
ExecStart=/usr/bin/Xvfb :99 -screen 0 1024x768x24 -ac +extension GLX +render -noreset
[Install]
WantedBy=multi-user.target' \
> /etc/systemd/system/xvfb.service"
Ative, inicie e verifique o status do xvfb.service
:
systemctl enable xvfb.service
systemctl start xvfb.service
systemctl status xvfb.service
No arquivo de configuração acima, há um FcgidInitialEnv DISPLAY ": 99"
que informa às instâncias do Servidor QGIS para usar o display no. 99. Se você estiver executando o servidor na área de trabalho, não há necessidade de instalar o xvfb e você deve simplesmente comentar com #
essa configuração específica no arquivo de configuração. Mais informações em https://www.itopen.it/qgis-server-setup-notes/.
Agora que o Apache sabe que ele deve responder solicitações para http://qgis.demo, também precisamos configurar o sistema do cliente para que ele saiba quem é qgis.demo
. Fazemos isso adicionando 127.0.0.1 qgis.demo
no arquivo hosts. Podemos fazer isso com sh -c "echo '127.0.0.1 qgis.demo' >> /etc/hosts"
. Substitua 127.0.0.1
pelo IP do seu servidor.
Nota
Remember that both the myhost.conf
and /etc/hosts
files should
be configured for our setup to work.
You can also test the access to your QGIS Server from other clients on the
network (e.g. Windows or macOS machines) by going to their /etc/hosts
file and point the myhost
name to whatever IP the server machine has on the
network. You can be sure that that specific IP is not 127.0.0.1
as that’s
the local IP, only accessible from the local machine. On *nix
machines the
hosts
file is located in /etc
, while on Windows it’s under
the C:\Windows\System32\drivers\etc
directory. Under Windows you
need to start your text editor with administrator privileges before opening
the hosts file.
Podemos testar um dos servidores qgis instalados com uma solicitação http da linha de comando com curl http://qgis.demo/cgi-bin/qgis_mapserv.fcgi
, que deve gerar:
<ServiceExceptionReport version="1.3.0" xmlns="https://www.opengis.net/ogc">
<ServiceException code="Service configuration error">Service unknown or unsupported</ServiceException>
</ServiceExceptionReport>
Nota
O curl pode ser instalado com apt install curl
.
Agora o Apache está configurado.
Além disso, no seu navegador da web, você pode verificar os recursos do servidor:
http://qgis.demo/cgi-bin/qgis_mapserv.fcgi?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetCapabilities
11.1.4.
Follow Along: Create another virtual host¶
Vamos criar outro host virtual Apache apontando para o Servidor QGIS. Você pode escolher o nome que quiser (coco.bango
, super.duper.training
, example.com
etc.), mas por uma questão de simplicidade, usaremos myhost
.
Vamos configurar o nome
myhost
para apontar para o IP do host local adicionando127.0.0.1 x
ao/etc/hosts
com o seguinte comando:sh -c "echo ' 127.0.0.1 myhost' >> /etc/hosts"
ou editando manualmente o arquivo comgedit /etc/hosts
.Podemos verificar que
myhost
aponta para o localhost executando no terminal o comandoping myhost
que deve gerar:
qgis@qgis:~$ ping myhost
PING myhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.024 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.029 ms
Vamos descobrir se podemos acessar o Servidor QGIS no site
myhost
fazendo:curl http://myhost/cgi-bin/qgis_mapserv.fcgi
ou acessando a URL no navegador de caixa Debian. Você provavelmente uma resposta assim:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /cgi-bin/qgis_mapserv.fcgi was not found on this server.</p>
<hr>
<address>Apache/2.4.25 (Debian) Server at myhost Port 80</address>
</body></html>
O Apache não sabe que ele deveria responder solicitações apontando para o servidor chamado
myhost
. Para configurar o host virtual, a maneira mais simples seria criar um arquivomyhost.conf
no diretório/etc/apache2/sites-available
que tenha o mesmo conteúdo queqgis .demo.conf
, exceto a linhaServerName
que deve serServerName myhost
. Você também pode alterar para onde os logs vão, caso contrário, os logs dos dois hosts virtuais seriam compartilhados, mas isso é opcional.Vamos agora ativar o host virtual com
a2ensite myhost.conf
e recarregar o serviço Apache comservice apache2 reload
.Se você tentar acessar novamente o URL http://myhost/cgi-bin/qgis_mapserv.fcgi, notará que tudo está funcionando agora!
11.1.5. In Conclusion¶
Você aprendeu como instalar versões diferentes do Servidor QGIS a partir de pacotes, como configurar o Apache com o Servidor QGIS, nas distribuições Linux baseadas no Debian.
11.1.6. What’s Next?¶
Now that you’ve installed QGIS Server and it’s accessible through the HTTP protocol, we need to learn how to access some of the services it can offer. The topic of the next lesson is to learn how to access QGIS Server WMS services.