Skip to content

Configuração de ambiente funcional com fluxo Postgresql -> geoserver -> geonode#14123

Closed
Gabriel-H2O-geo wants to merge 1 commit intoGeoNode:masterfrom
h2o-innovation:dev
Closed

Configuração de ambiente funcional com fluxo Postgresql -> geoserver -> geonode#14123
Gabriel-H2O-geo wants to merge 1 commit intoGeoNode:masterfrom
h2o-innovation:dev

Conversation

@Gabriel-H2O-geo
Copy link
Copy Markdown

Ambiente Local GeoNode com Banco Externo

Fluxo de Dados

Banco Externo (PostGIS) → GeoServer → Publica Camada → GeoNode (Catálogo)

Arquitetura Docker

Arquivo: docker-compose-local.yml — 9 serviços

Serviço Imagem Porta Função
django geonode/geonode:local (build local) Aplicação GeoNode (Django)
celery geonode/geonode:local (reusa imagem) Workers assíncronos + Beat scheduler
geonode (nginx) geonode/nginx:1.28.0-v1 80, 443 Proxy reverso, serve estáticos
geoserver geonode/geoserver:2.27.5 8080 Servidor OGC (WMS/WFS/WCS)
db postgis/postgis:15-3.5 5434 Banco interno GeoNode
redis redis:7-alpine 6379 Broker Celery
memcached memcached:alpine 11211 Cache
data-dir-conf geonode/geoserver_data:2.27.5 Inicializa data dir do GeoServer
letsencrypt geonode/letsencrypt:latest Certificados SSL (desabilitado em dev)

Acesso ao banco externo: via extra_hosts: host.docker.internal:host-gateway, permitindo que containers acessem hosts na rede do Docker host.


Configuração de Credenciais

Nenhuma credencial é versionada. Arquivos sensíveis estão no .gitignore:

.env              # variáveis do stack Docker (gerado por create-envfile.py)
.env_external     # credenciais do banco externo
.env_local        # variáveis auxiliares locais
.env_dev / .env_test / .devcontainer/.env

Banco Externo — .env_external

Template disponível em .env_external.sample:

EXT_DB_HOST=         # IP/hostname do servidor PostGIS externo
EXT_DB_PORT=5432
EXT_DB_NAME=         # nome do banco (ex: db_geo_prd)
EXT_DB_SCHEMA=public # schema onde estão as tabelas
EXT_DB_USER=         # usuário com permissão de leitura
EXT_DB_PASS=         # senha do usuário

Registro do Datastore no GeoServer

Script: setup_external_datastore.sh

  • Lê credenciais de .env_external (ou variáveis de ambiente)
  • Registra o banco externo como datastore PostGIS no GeoServer via REST API
  • Valida conectividade antes de configurar
  • Execução: bash setup_external_datastore.sh (após stack estar healthy)

Sincronização Automática GeoServer → GeoNode

Arquivo: geonode/settings.pyCELERY_BEAT_SCHEDULE

CELERY_BEAT_SCHEDULE = {
    "sync-geoserver-layers": {
        "task": "geonode.geoserver.tasks.geoserver_update_datasets",
        "schedule": int(os.environ.get("GEOSERVER_SYNC_INTERVAL", "120")),  # segundos
        "kwargs": {
            "workspace": "geonode",
            "store": "db_geo_prd",
            "owner": "admin",
            "skip_geonode_registered": True,
            "execute_signals": True,
        },
    },
}

Comportamento:

  • A cada 120 segundos (configurável via GEOSERVER_SYNC_INTERVAL no .env), o Celery Beat verifica novas tabelas no datastore db_geo_prd do GeoServer
  • Tabelas novas são automaticamente publicadas como camadas no GeoServer e registradas como datasets no catálogo GeoNode
  • skip_geonode_registered=True evita reprocessar camadas já sincronizadas
  • execute_signals=True dispara geração de thumbnails e metadados

Como Subir o Ambiente

# 1. Gerar .env (se ainda não existe)
python create-envfile.py

# 2. Criar .env_external com credenciais do banco externo
cp .env_external.sample .env_external
# editar .env_external com os dados reais

# 3. Subir stack
docker compose -f docker-compose-local.yml up -d --build

# 4. Registrar datastore externo no GeoServer
bash setup_external_datastore.sh

Ou usar o script automatizado: bash start_local.sh


Acessos

Serviço URL Credenciais padrão
GeoNode http://localhost/ admin / admin
GeoServer (via proxy) http://localhost/geoserver/web/ OAuth2 via GeoNode
GeoServer (direto) http://localhost:8080/geoserver admin / geoserver

Nota: O acesso ao GeoServer via :8080 usa autenticação básica. Via proxy Nginx (/geoserver/web/), usa OAuth2 integrado com GeoNode.


Arquivos Adicionados/Modificados

Arquivo Descrição
docker-compose-local.yml Stack Docker completo (9 serviços)
setup_external_datastore.sh Registro do banco externo no GeoServer
.env_external.sample Template de credenciais do banco externo
start_local.sh Script de inicialização automatizada
status.sh Health check de todos os serviços
SETUP_REFERENCE.txt Referência completa para produção
.gitattributes Força LF em scripts (evita erro CRLF no Linux)
.gitignore Atualizado com arquivos sensíveis
geonode/settings.py Celery Beat schedule para sync automático

Segurança

  • Nenhuma credencial está versionada no repositório
  • Arquivos .env* estão no .gitignore
  • setup_external_datastore.sh lê credenciais de variáveis de ambiente / .env_external
  • Para produção: alterar senhas padrão, habilitar HTTPS, configurar ALLOWED_HOSTS

@cla-bot
Copy link
Copy Markdown

cla-bot bot commented Apr 10, 2026

Thank you for your pull request and welcome to our community. We could not parse the GitHub identity of the following contributors: Gabriel Leandro.
This is most likely caused by a git client misconfiguration; please make sure to:

  1. check if your git client is configured with an email to sign commits git config --list | grep email
  2. If not, set it up using git config --global user.email email@example.com
  3. Make sure that the git commit email is configured in your GitHub account settings, see https://github.com/settings/emails

@gitguardian
Copy link
Copy Markdown

gitguardian bot commented Apr 10, 2026

⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

Since your pull request originates from a forked repository, GitGuardian is not able to associate the secrets uncovered with secret incidents on your GitGuardian dashboard.
Skipping this check run and merging your pull request will create secret incidents on your GitGuardian dashboard.

🔎 Detected hardcoded secret in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
- - Curl Username Password 1d7b77c SETUP_REFERENCE.txt View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a local deployment stack for GeoNode with support for an external PostGIS database, including Docker Compose configurations, initialization scripts, and automated layer synchronization via Celery Beat. The review feedback highlights several critical improvements: the need to include the .env_external file in the Docker environment configuration, the replacement of hardcoded datastore names with environment variables in both settings and status scripts, and the requirement for more robust JSON construction in the setup script to handle special characters in database passwords.

image: geonode/geonode:local
restart: unless-stopped
env_file:
- .env
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

O arquivo .env_external não está incluído na configuração env_file do serviço Django/Celery. Como as variáveis de conexão ao banco externo (como EXT_DB_NAME ou GS_DATASTORE_NAME) são definidas nesse arquivo, elas não estarão disponíveis para a aplicação GeoNode em tempo de execução, o que fará com que a tarefa do Celery Beat falhe ao tentar localizar o datastore correto.

    - .env
    - .env_external

"schedule": int(os.environ.get("GEOSERVER_SYNC_INTERVAL", "120")),
"kwargs": {
"workspace": "geonode",
"store": "db_geo_prd",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

O nome do datastore está fixo como "db_geo_prd". No entanto, o script setup_external_datastore.sh permite que o usuário customize este nome através das variáveis GS_DATASTORE_NAME ou EXT_DB_NAME. Se o usuário alterar essas configurações no arquivo .env_external, a sincronização automática de camadas falhará por não encontrar o datastore com o nome esperado.

Suggested change
"store": "db_geo_prd",
"store": os.environ.get("GS_DATASTORE_NAME", os.environ.get("EXT_DB_NAME", "db_geo_prd")),

{\"@key\": \"database\", \"\$\": \"${DB_NAME}\"},
{\"@key\": \"schema\", \"\$\": \"${DB_SCHEMA}\"},
{\"@key\": \"user\", \"\$\": \"${DB_USER}\"},
{\"@key\": \"passwd\", \"\$\": \"${DB_PASS}\"},
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

A inserção direta da variável ${DB_PASS} dentro do payload JSON via string literal é vulnerável a erros de sintaxe. Se a senha do banco de dados contiver caracteres especiais, como aspas duplas ("), o JSON enviado ao GeoServer ficará malformado, resultando em erro na requisição. Recomenda-se o uso de uma ferramenta como jq para construir o JSON de forma segura ou garantir o escape manual dos caracteres.

echo "[Datastore externo]"
DS=$(docker exec geoserver4geonode curl -s -o /dev/null -w "%{http_code}" \
-u "admin:geoserver" \
"http://localhost:8080/geoserver/rest/workspaces/geonode/datastores/db_geo_prd.json" 2>/dev/null)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

O script de status possui o nome do datastore (db_geo_prd) fixo no caminho da URL da API. Se o ambiente for configurado com um nome de banco de dados diferente, este script reportará erroneamente que o datastore não está configurado.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant