One place for hosting & domains

      October 2018

      Como Instalar e Usar o Composer no Ubuntu 18.04


      Uma versão anterior desse tutorial foi escrito por Brennen Bearnes.

      Introdução

      O Composer é uma ferramenta popular de gerenciamento de dependências para o PHP, criado principalmente para facilitar a instalação e atualização para dependências de projeto. Ele verificará de quais outros pacotes um projeto específico depende e os instalará para você, usando as versões apropriadas de acordo com os requisitos do projeto.

      Neste tutorial, você instalará e começará a usar o Composer em um sistema Ubuntu 18.04.

      Pré-requisitos

      Para completar este tutorial, você vai precisar de:

      Passo 1 — Instalando as Dependências

      Antes de você baixar e instalar o Composer, você deve certificar-se de que seu servidor tenha todas as dependências instaladas.

      Primeiro, atualize o cache do gerenciador de pacotes executando:

      Agora, vamos instalar as dependências. Precisaremos do curl para que possamos baixar o Composer e o phi-cli para instalação e execução dele. O pacote php-mbstring é necessário para fornecer funções para a biblioteca que estaremos utilizando. O git é utilizado pelo Composer para baixar as dependências de projeto, e o unzip para a extração dos pacotes compactados. Tudo pode ser instalado com o seguinte comando:

      • sudo apt install curl php-cli php-mbstring git unzip

      Com os pré-requisitos instalados, podemos instalar o Composer propriamente dito.

      Passo 2 — Baixando e Instalando o Composer

      O Composer fornece um instalador, escrito em PHP. Iremos baixá-lo, verificar que o mesmo não está corrompido, e então utilizá-lo para instalar o Composer.

      Certtifique-se de você está em seu diretório home, em seguida baixe o instalador utilizando o curl:

      • cd ~
      • curl -sS https://getcomposer.org/installer -o composer-setup.php

      A seguir, verifique se o instalador corresponde ao hash SHA-384 para o instalador mais recente encontrado na página Composer Public Keys / Signatures. Copie o hash desta página e armazene-o em uma variável do shell.

      • HASH=544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9180f061

      Certifique-se de que você substituiu o hash mais recente para o valor destacado.

      Agora, execute o seguinte script PHP para verificar que o script de instalação é seguro para execução:

      • php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

      Você verá a seguinte saída:

      Output

      Installer verified
      

      Se você vir Installer corrupt, então você vai precisar baixar novamente o script de instalação e conferir minuciosamente se você está utilizando o hash correto. Depois, execute o comando para verificar o instalador novamente. Uma vez que você tenha o instalador verificado, você pode continuar.

      Para instalar o composer globalmente, utilize o seguinte comando que irá baixar e instalar o Composer como um comando disponível para todo o sistema chamado composer, dentro de /usr/local/bin:

      • sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

      Você verá a seguinte saída:

      Output

      All settings correct for using Composer Downloading... Composer (version 1.6.5) successfully installed to: /usr/local/bin/composer Use it: php /usr/local/bin/composer

      Para testar a sua instalação, execute:

      E você verá esta saída mostrando a versão e os argumentos do Composer.

      Output

      ______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ / __ `__ / __ / __ / ___/ _ / ___/ / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ / ____/____/_/ /_/ /_/ .___/____/____/___/_/ /_/ Composer version 1.6.5 2018-05-04 11:44:59 Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --profile Display timing and memory usage information --no-plugins Whether to disable plugins. -d, --working-dir=WORKING-DIR If specified, use the given directory as working directory. -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug . . .

      Isso verifica que o Composer foi instalado com sucesso em seu sistema e está disponível de maneira global para todos.

      Nota: se você preferir ter executáveis do Composer separados para cada projeto que você hospedar neste servidor, você poderá instalá-lo localmente, em uma base por projeto. Usuários do NPM estarão familiarizados com esta abordagem. Este método é útil também quando seu usuário de sistema não tem permissão para instalar software para todo o sistema.

      Para fazer isto, utilize o comando php composer-setup.php. Isto irá gerar um arquivo composer.phar em seu diretório atual, que pode ser executado com ./composer.pharcomando.

      Agora, vamos dar uma olhada em como utilizar o Composer para gerenciar dependências.

      Passo 3 — Usando o Composer em um Projeto PHP

      Projetos PHP frequentemente dependem de bibliotecas externas, e o gerenciamento dessas dependências e suas versões pode ser complicado. O Composer resolve isso rastreando suas dependências e facilitando a instalação delas por outras pessoas.

      Para usar o Composer no seu projeto, você precisa de um arquivo composer-json. O arquivo composer.json diz ao Composer quais dependências ele precisa baixar para o seu projeto, e para quais versões de cada pacote está permitida a instalação. Isto é extremamente importante para manter o seu projeto consistente e evitar a instalação de versões instáveis que podem causar problemas de compatibilidade com versões anteriores.

      Você não precisa criar este arquivo manualmente - é fácil cometer erros de sintaxe quando você faz isso. O Composer gera automaticamente o arquivo composer.json quando você adiciona uma dependêcia para o seu projeto utilizando o comando require. Você pode adicionar dependências adicionais da mesma forma, sem a necessidade de editar manualmente este arquivo.

      O processo de se utilizar o Composer para instalar um pacote como dependência em um projeto envolve os sequintes passos:

      • Identificar qual tipo de biblioteca a aplicação precisa.

      • Pesquisar uma biblioteca de código aberto adequada em Packagist.org, o repositório de pacotes oficial para o Composer.

      • Escolher o pacote do qual você quer depender.

      • Executar composer require para incluir a dependência no arquivo composer.json e instalar o pacote.

      Vamos tentar isso com uma aplicação de demonstração.

      O objetivo dessa aplicação é transformar uma dada sentença em uma string com URL amigável - um slug. Isso é comumente usado para converter títulos de páginas em caminhos de URL (como a parte final da URL deste tutorial).

      Vamos começar criando o diretório para nosso projeto. Vamos chamá-lo de slugify:

      • cd ~
      • mkdir slugify
      • cd slugify

      Agora é a hora de pesquisar no Packagist.org um pacote que possa nos ajudar a gerar slugs. Se você pesquisar pelo termo "slug" no Packagist, você obterá um resultado semelhante a esse:

      Você verá dois números do lado direito de cada pacote na lista. O número no topo representa quantas vezes o pacote foi instalado, e o número embaixo mostra quantas vezes um pacote recebeu estrelas no GitHub. Você pode reorganizar os resultados da pesquisa com base nesses números (procure os dois ícones no lado direito da barra de pesquisa). De um modo geral, pacotes com mais instalações e mais estrelas tendem a ser mais estáveis, já que muitas pessoas estão usando. Também é importante verificar a descrição do pacote quanto à relevância para garantir que é o que você precisa.

      Precisamos de um conversor siples de string-para-slug. Nos resultados da pesquisa, o pacote cocur/slugify parece ser uma boa escolha, com uma quantidade razoável de instalações e estrelas. (O pacote está um pouco mais abaixo na página do que a imagem mostra.)

      Os pacotes no Packagist tem um nome de vendor e um nome de package ou pacote. Cada pacote tem um identificador único (um namespace) no mesmo formato que o GitHub utiliza para seus repositórios, no formato vendor/package. A biblioteca que queremos instalar utiliza o namespace cocur/slugif. Você precisa do namespace para requerer o pacote em seu projeto.

      Agora que você sabe exatamente quais pacotes você quer instalar, execute composer require para incluí-los como uma dependência e gere também o arquivo composer.json para o projeto:

      • composer require cocur/slugify

      Você verá esta saída enquanto o Composer baixa a dependência:

      Output

      Using version ^3.1 for cocur/slugify ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Installing cocur/slugify (v3.1): Downloading (100%) Writing lock file Generating autoload files

      Como você pode ver pela saída, o Composer decide automaticamente qual versão do pacote utilizar. Se você verificar o diretório do seu projeto agora, ele irá conter dois novos arquivos: composer.json e composer.lock, e um diretório vendor:

      Output

      • total 12
      • -rw-rw-r-- 1 sammy sammy 59 Jul 11 16:40 composer.json
      • -rw-rw-r-- 1 sammy sammy 2934 Jul 11 16:40 composer.lock
      • drwxrwxr-x 4 sammy sammy 4096 Jul 11 16:40 vendor

      O arquivo composer.lock é usado para guardar informações sobre quais versões de cada pacote estão instaladas, e garantir que as mesmas versões sejam usadas se alguém clonar seu projeto e instalar suas dependências. O diretório vendor é onde as dependências do projeto estão localizadas. A pasta vendor não precisa ter o commit realizado no controle de versão - você só precisa incluir os arquivos composer.json e composer.lock.

      Ao instalar um projeto que já contém um arquivo composer.json, execute composer install para fazer o download das dependências do projeto.

      Vamos dar uma olhada rápida nas restrições de versão. Se você verificar o conteúdo do seu arquivo composer.json, verá algo como isto:

      Output

      { "require": { "cocur/slugify": "^3.1" } } sam

      Você deve ter notado o caractere especial ^ antes do número da versão no composer.json. O Composer suporta várias restrições e formatos diferentes para definir a versão do pacote necessária, a fim de fornecer flexibilidade e, ao mesmo tempo, manter seu projeto estável. O operador cirunflexo (^) utilizado pelo arquivo auto-gerado composer.json é o operador recomendado para a máxima interoperabilidade, seguindo o versionamento semântico. Nesse caso, ele define 3.1 como a versão mínima compatível, e permite atualizar para quaisquer versões futuras abaixo da 4.00.

      De modo geral, você não precisará adulterar restrições de versão em seu arquivo composer.json. Contudo, algumas situações podem exigir que você edite manualmente as restrições - por exemplo, quando uma nova versão principal de sua biblioteca obrigatória é lançada e você deseja atualizar, ou quando a biblioteca que você deseja usar não segue o versionamento semântico.

      Aqui estão alguns exemplos para entender melhor como funcionam as restrições de versão do Composer:

      RestriçãoSignificadoVersões de Exemplo Permitidas
      ^1.0>= 1.0 < 2.01.0, 1.2.3, 1.9.9
      ^1.1.0>= 1.1.0 < 2.01.1.0, 1.5.6, 1.9.9
      ~1.0>= 1.0 < 2.0.01.0, 1.4.1, 1.9.9
      ~1.0.0>= 1.0.0 < 1.11.0.0, 1.0.4, 1.0.9
      1.2.11.2.11.2.1
      1.*>= 1.0 < 2.01.0.0, 1.4.5, 1.9.9
      1.2.*>= 1.2 < 1.31.2.0, 1.2.3, 1.2.9

      Para uma visão mais aprofundada das restrições de versão do Composer, consulte a documentação oficial.

      Em seguida, vamos ver como carregar dependências automaticamente com o Composer.

      Passo 4 — Incluindo o Script Autoload

      Como o próprio PHP não carrega classes automaticamente, o Composer fornece um script de carregamento automático que você pode incluir em seu projeto para obter o carregamento automático de graça. Isso facilita muito o trabalho com suas dependências.

      A única coisa que você precisa fazer é incluir o arquivo vendor/autoload.php em seus scripts PHP antes de qualquer instanciamento de classe. Este arquivo é gerado automaticamente pelo Composer quando você adiciona sua primeira dependência.

      Vamos experimentar isso em nossa aplicação. Crie o arquivo test.php e abra-o em seu editor de textos:

      Adicione o seguinte código que traz o arquivo vendor/autoload.php, carrega a dependência cocur/slugify, e a utiliza para criar um slug:

      test.php

      
      <?php
      require __DIR__ . '/vendor/autoload.php';
      
      use CocurSlugifySlugify;
      
      $slugify = new Slugify();
      
      echo $slugify->slugify('Hello World, this is a long sentence and I need to make a slug from it!');
      

      Salve o arquivo e saia do editor.

      Agora, execute o script:

      Isso produz a saída hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it.

      Dependências precisam de atualizações quando novas versões são lançadas, então vamos ver como lidar com isso.

      Passo 5 — Atualizando as Dependências de Projeto

      Sempre que você quiser atualizar suas dependências de projeto para versões mais recentes, execute o comando update:

      Isso irá verificar as versões mais recentes das bibliotecas necessárias em seu projeto. Se uma versão mais nova for encontrada e for compatível com a restrição de versão definida no arquivo composer.json, o Composer substituirá a versão anterior instalada. O arquivo composer.lock será atualizado para refletir estas mudanças.

      Você também pode atualizar uma ou mais bibliotecas específicas, especificando-as assim:

      • composer update vendor/package vendor2/package2

      Certifique-se de verificar seus arquivos composer.json ecomposer.lock depois de atualizar suas dependências para que outras pessoas possam instalar essas versões mais novas.

      Conclusão

      O Composer é uma ferramenta poderosa que todo desenvolvedor de PHP deve ter em seu cinto de utilidades. Neste tutorial você instalou o Composer e o utilizou em um projeto simples. Agora você sabe como instalar e atualizar dependências.

      Além de fornecer uma maneira fácil e confiável de gerenciar dependências de projetos, ele também estabelece um novo padrão de fato para compartilhar e descobrir pacotes PHP criados pela comunidade.

      Brian Hogan



      Source link

      An Introduction to the Kubernetes DNS Service


      Introduction

      The Domain Name System (DNS) is a system for associating various types of information – such as IP addresses – with easy-to-remember names. By default most Kubernetes clusters automatically configure an internal DNS service to provide a lightweight mechanism for service discovery. Built-in service discovery makes it easier for applications to find and communicate with each other on Kubernetes clusters, even when pods and services are being created, deleted, and shifted between nodes.

      The implementation details of the Kubernetes DNS service have changed in recent versions of Kubernetes. In this article we will take a look at both the kube-dns and CoreDNS versions of the Kubernetes DNS service. We will review how they operate and the DNS records that Kubernetes generates.

      To gain a more thorough understanding of DNS before you begin, please read An Introduction to DNS Terminology, Components, and Concepts. For any Kubernetes topics you may be unfamiliar with, you could read An Introduction to Kubernetes.

      What Does the Kubernetes DNS Service Provide?

      Before Kubernetes version 1.11, the Kubernetes DNS service was based on kube-dns. Version 1.11 introduced CoreDNS to address some security and stability concerns with kube-dns.

      Regardless of the software handling the actual DNS records, both implementations work in a similar manner:

      • A service named kube-dns and one or more pods are created.
      • The kube-dns service listens for service and endpoint events from the Kubernetes API and updates its DNS records as needed. These events are triggered when you create, update or delete Kubernetes services and their associated pods.
      • kubelet sets each new pod’s /etc/resolv.conf nameserver option to the cluster IP of the kube-dns service, with appropriate search options to allow for shorter hostnames to be used:

        resolv.conf

        nameserver 10.32.0.10
        search namespace.svc.cluster.local svc.cluster.local cluster.local
        options ndots:5
        
      • Applications running in containers can then resolve hostnames such as example-service.namespace into the correct cluster IP addresses.

      Example Kubernetes DNS Records

      The full DNS A record of a Kubernetes service will look like the following example:

      service.namespace.svc.cluster.local
      

      A pod would have a record in this format, reflecting the actual IP address of the pod:

      10.32.0.125.namespace.pod.cluster.local
      

      Additionally, SRV records are created for a Kubernetes service’s named ports:

      _port-name._protocol.service.namespace.svc.cluster.local
      

      The result of all this is a built-in, DNS-based service discovery mechanism, where your application or microservice can target a simple and consistent hostname to access other services or pods on the cluster.

      Search Domains and Resolving Shorter Hostnames

      Because of the search domain suffixes listed in the resolv.conf file, you often won’t need to use the full hostname to contact another service. If you’re addressing a service in the same namespace, you can use just the service name to contact it:

      other-service
      

      If the service is in a different namespace, add it to the query:

      other-service.other-namespace
      

      If you’re targeting a pod, you’ll need to use at least the following:

      pod-ip.other-namespace.pod
      

      As we saw in the default resolv.conf file, only .svc suffixes are automatically completed, so make sure you specify everything up to .pod.

      Now that we know the practical uses of the Kubernetes DNS service, let’s run through some details on the two different implementations.

      Kubernetes DNS Implementation Details

      As noted in the previous section, Kubernetes version 1.11 introduced new software to handle the kube-dns service. The motivation for the change was to increase the performance and security of the service. Let’s take a look at the original kube-dns implementation first.

      kube-dns

      The kube-dns service prior to Kubernetes 1.11 is made up of three containers running in a kube-dns pod in the kube-system namespace. The three containers are:

      • kube-dns: a container that runs SkyDNS, which performs DNS query resolution
      • dnsmasq: a popular lightweight DNS resolver and cache that caches the responses from SkyDNS
      • sidecar: a sidecar container that handles metrics reporting and responds to health checks for the service

      Security vulnerabilities in Dnsmasq, and scaling performance issues with SkyDNS led to the creation of a replacement system, CoreDNS.

      CoreDNS

      As of Kubernetes 1.11 a new Kubernetes DNS service, CoreDNS has been promoted to General Availability. This means that it’s ready for production use and will be the default cluster DNS service for many installation tools and managed Kubernetes providers.

      CoreDNS is a single process, written in Go, that covers all of the functionality of the previous system. A single container resolves and caches DNS queries, responds to health checks, and provides metrics.

      In addition to addressing performance- and security-related issues, CoreDNS fixes some other minor bugs and adds some new features:

      • Some issues with incompatibilities between using stubDomains and external services have been fixed
      • CoreDNS can enhance DNS-based round-robin load balancing by randomizing the order in which it returns certain records
      • A feature called autopath can improve DNS response times when resolving external hostnames, by being smarter about iterating through each of the search domain suffixes listed in resolv.conf
      • With kube-dns 10.32.0.125.namespace.pod.cluster.local would always resolve to 10.32.0.125, even if the pod doesn’t actually exist. CoreDNS has a “pods verified” mode that will only resolve successfully if a pod exists with the right IP and in the right namespace.

      For more information on CoreDNS and how it differs from kube-dns, you can read the Kubernetes CoreDNS GA announcement.

      Additional Configuration Options

      Kubernetes operators often want to customize how their pods and containers resolve certain custom domains, or need to adjust the upstream nameservers or search domain suffixes configured in resolv.conf. You can do this with the dnsConfig option of your pod’s spec:

      example_pod.yaml

      apiVersion: v1
      kind: Pod
      metadata:
        namespace: example
        name: custom-dns
      spec:
        containers:
          - name: example
            image: nginx
        dnsPolicy: "None"
        dnsConfig:
          nameservers:
            - 203.0.113.44
          searches:
            - custom.dns.local
      

      Updating this config will rewrite a pod’s resolv.conf to enable the changes. The configuration maps directly to the standard resolv.conf options, so the above config would create a file with nameserver 203.0.113.44 and search custom.dns.local lines.

      Conclusion

      In this article we covered the basics of what the Kubernetes DNS service provides to developers, showed some example DNS records for services and pods, discussed how the system is implemented on different Kubernetes versions, and highlighted some additional configuration options available to customize how your pods resolve DNS queries.

      For more information on the Kubernetes DNS service, please refer to the official Kubernetes DNS for Services and Pods documentation.



      Source link

      How to Install and Configure pgAdmin 4 in Server Mode


      Introduction

      pgAdmin is an open-source administration and development platform for PostgreSQL and its related database management systems. Written in Python and jQuery, it supports all the features found in PostgreSQL. You can use pgAdmin to do everything from writing basic SQL queries to monitoring your databases and configuring advanced database architectures.

      In this tutorial, we’ll walk through the process of installing and configuring the latest version of pgAdmin onto an Ubuntu 18.04 server, accessing pgAdmin through a web browser, and connecting it to a PostgreSQL database on your server.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Installing pgAdmin and its Dependencies

      As of this writing, the most recent version of pgAdmin is pgAdmin 4, while the most recent version available through the official Ubuntu repositories is pgAdmin 3. pgAdmin 3 is no longer supported though, and the project maintainers recommend installing pgAdmin 4. In this step, we will go over the process of installing the latest version of pgAdmin 4 within a virtual environment (as recommended by the project’s development team) and installing its dependencies using apt.

      To begin, update your server’s package index if you haven’t done so recently:

      Next, install the following dependencies. These include libgmp3-dev, a multiprecision arithmetic library; libpq-dev, which includes header files and a static library that helps communication with a PostgreSQL backend; and libapache2-mod-wsgi-py3, an Apache module that allows you to host Python-based web applications within Apache:

      • sudo apt install libgmp3-dev libpq-dev libapache2-mod-wsgi-py3

      Following this, create a few directories where pgAdmin will store its sessions data, storage data, and logs:

      • sudo mkdir -p /var/lib/pgadmin4/sessions
      • sudo mkdir /var/lib/pgadmin4/storage
      • sudo mkdir /var/log/pgadmin4

      Then, change ownership of these directories to your non-root user and group. This is necessary because they are currently owned by your root user, but we will install pgAdmin from a virtual environment owned by your non-root user, and the installation process involves creating some files within these directories. After the installation, however, we will change the ownership over to the www-data user and group so it can be served to the web:

      • sudo chown -R sammy:sammy /var/lib/pgadmin4
      • sudo chown -R sammy:sammy /var/log/pgadmin4

      Next, open up your virtual environment. Navigate to the directory your programming environment is in and activate it. Following the naming conventions of the prerequisite Python 3 tutorial, we’ll go to the environments directory and activate the my_env environment:

      • cd environments/
      • source my_env/bin/activate

      Following this, download the pgAdmin 4 source code onto your machine. To find the latest version of the source code, navigate to the pgAdmin 4 (Python Wheel) Download page and click the link for the latest version (v3.4, as of this writing). This will take you to a Downloads page on the PostgreSQL website. Once there, copy the file link that ends with .whl — the standard built-package format used for Python distributions. Then go back to your terminal and run the following wget command, making sure to replace the link with the one you copied from the PostgreSQL site, which will download the .whl file to your server:

      • wget https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v3.4/pip/pgadmin4-3.4-py2.py3-none-any.whl

      Next install the wheel package, the reference implementation of the wheel packaging standard. A Python library, this package serves as an extension for building wheels and includes a command line tool for working with .whl files:

      • python -m pip install wheel

      Then install pgAdmin 4 package with the following command:

      • python -m pip install pgadmin4-3.4-py2.py3-none-any.whl

      That takes care of installing pgAdmin and its dependencies. Before connecting it to your database, though, there are a few changes you’ll need to make to the program’s configuration.

      Step 2 — Configuring pgAdmin 4

      Although pgAdmin has been installed on your server, there are still a few steps you must go through to ensure it has the permissions and configurations needed to allow it to correctly serve the web interface.

      pgAdmin’s main configuration file, config.py, is read before any other configuration file. Its contents can be used as a reference point for further configuration settings that can be specified in pgAdmin’s other config files, but to avoid unforeseen errors, you should not edit the config.py file itself. We will add some configuration changes to a new file, named config_local.py, which will be read after the primary one.

      Create this file now using your preferred text editor. Here, we will use nano:

      • nano my_env/lib/python3.6/site-packages/pgadmin4/config_local.py

      In your editor, add the following content:

      environments/my_env/lib/python3.6/site-packages/pgadmin4/config_local.py

      LOG_FILE = '/var/log/pgadmin4/pgadmin4.log'
      SQLITE_PATH = '/var/lib/pgadmin4/pgadmin4.db'
      SESSION_DB_PATH = '/var/lib/pgadmin4/sessions'
      STORAGE_DIR = '/var/lib/pgadmin4/storage'
      SERVER_MODE = True
      

      Here are what these five directives do:

      • LOG_FILE: this defines the file in which pgAdmin’s logs will be stored.
      • SQLITE_PATH: pgAdmin stores user-related data in an SQLite database, and this directive points the pgAdmin software to this configuration database. Because this file is located under the persistent directory /var/lib/pgadmin4/, your user data will not be lost after you upgrade.
      • SESSION_DB_PATH: specifies which directory will be used to store session data.
      • STORAGE_DIR: defines where pgAdmin will store other data, like backups and security certificates.
      • SERVER_MODE: setting this directive to True tells pgAdmin to run in Server mode, as opposed to Desktop mode.

      Notice that each of these file paths point to the directories you created in Step 1.

      After adding these lines, save and close the file (press CTRL + X, followed by Y and then ENTER). With those configurations in place, run the pgAdmin setup script to set your login credentials:

      • python my_env/lib/python3.6/site-packages/pgadmin4/setup.py

      After running this command, you will see a prompt asking for your email address and a password. These will serve as your login credentials when you access pgAdmin later on, so be sure to remember or take note of what you enter here:

      Output

      . . . Enter the email address and password to use for the initial pgAdmin user account: Email address: [email protected] Password: Retype password:

      Following this, deactivate your virtual environment:

      Recall the file paths you specified in the config_local.py file. These files are held within the directories you created in Step 1, which are currently owned by your non-root user. They must, however, be accessible by the user and group running your web server. By default on Ubuntu 18.04, these are the www-data user and group, so update the permissions on the following directories to give www-data ownership over both of them:

      • sudo chown -R www-data:www-data /var/lib/pgadmin4/
      • sudo chown -R www-data:www-data /var/log/pgadmin4/

      With that, pgAdmin is fully configured. However, the program isn't yet being served from your server, so it remains inaccessible. To resolve this, we will configure Apache to serve pgAdmin so you can access its user interface through a web browser.

      Step 3 — Configuring Apache

      The Apache web server uses virtual hosts to encapsulate configuration details and host more than one domain from a single server. If you followed the prerequisite Apache tutorial, you may have set up an example virtual host file under the name example.com.conf, but in this step we will create a new one from which we can serve the pgAdmin web interface.

      To begin, make sure you're in your root directory:

      Then create a new file in your /sites-available/ directory called pgadmin4.conf. This will be your server’s virtual host file:

      • sudo nano /etc/apache2/sites-available/pgadmin4.conf

      Add the following content to this file, being sure to update the highlighted parts to align with your own configuration:

      /etc/apache2/sites-available/pgadmin4.conf

      <VirtualHost *>
          ServerName your_server_ip
      
          WSGIDaemonProcess pgadmin processes=1 threads=25 python-home=/home/sammy/environments/my_env
          WSGIScriptAlias / /home/sammy/environments/my_env/lib/python3.6/site-packages/pgadmin4/pgAdmin4.wsgi
      
          <Directory "/home/sammy/environments/my_env/lib/python3.6/site-packages/pgadmin4/">
              WSGIProcessGroup pgadmin
              WSGIApplicationGroup %{GLOBAL}
              Require all granted
          </Directory>
      </VirtualHost>
      

      Save and close the virtual host file. Next, use the a2dissite script to disable the default virtual host file, 000-default.conf:

      • sudo a2dissite 000-default.conf

      Note: If you followed the prerequisite Apache tutorial, you may have already disabled 000-default.conf and set up an example virtual host configuration file (named example.com.conf in the prerequisite). If this is the case, you will need to disable the example.com.conf virtual host file with the following command:

      • sudo a2dissite example.com.conf

      Then use the a2ensite script to enable your pgadmin4.conf virtual host file. This will create a symbolic link from the virtual host file in the /sites-available/ directory to the /sites-enabled/ directory:

      • sudo a2ensite pgadmin4.conf

      Following this, test that your configuration file’s syntax is correct:

      If your configuration file is all in order, you will see Syntax OK. If you see an error in the output, reopen the pgadmin4.conf file and double check that your IP address and file paths are all correct, then rerun the configtest.

      Once you see Syntax OK in your output, restart the Apache service so it reads your new virtual host file:

      • sudo systemctl restart apache2

      pgAdmin is now fully installed and configured. Next, we'll go over how to access pgAdmin from a browser before connecting it to your PostgreSQL database.

      Step 4 — Accessing pgAdmin

      On your local machine, open up your preferred web browser and navigate to your server’s IP address:

      http://your_server_ip
      

      Once there, you’ll be presented with a login screen similar to the following:

      pgAdmin login screen

      Enter the login credentials you defined in Step 2, and you’ll be taken to the pgAdmin Welcome Screen:

      pgAdmin Welcome Page

      Now that you've confirmed you can access the pgAdmin interface, all that's left to do is to connect pgAdmin to your PostgreSQL database. Before doing so, though, you'll need to make one minor change to your PostgreSQL superuser's configuration.

      Step 5 — Configuring your PostgreSQL User

      If you followed the prerequisite PostgreSQL tutorial, you should already have PostgreSQL installed on your server with a new superuser role and database set up.

      By default in PostgreSQL, you authenticate as database users using the "Identification Protocol," or "ident," authentication method. This involves PostgreSQL taking the client's Ubuntu username and using it as the allowed database username. This can allow for greater security in many cases, but it can also cause issues in instances where you'd like an outside program, such as pgAdmin, to connect to one of your databases. To resolve this, we will set a password for this PostgreSQL role which will allow pgAdmin to connect to your database.

      From your terminal, open the PostgreSQL prompt under your superuser role:

      From the PostgreSQL prompt, update the user profile to have a strong password of your choosing:

      • ALTER USER sammy PASSWORD 'password';

      Then exit the PostgreSQL prompt:

      Next, go back to the pgAdmin 4 interface in your browser, and locate the Browser menu on the left hand side. Right-click on Servers to open a context menu, hover your mouse over Create, and click Server….

      Create Server context menu

      This will cause a window to pop up in your browser in which you'll enter info about your server, role, and database.

      In the General tab, enter the name for this server. This can be anything you'd like, but you may find it helpful to make it something descriptive. In our example, the server is named Sammy-server-1.

      Create Server - General tab

      Next, click on the Connection tab. In the Host name/address field, enter localhost. The Port should be set to 5432 by default, which will work for this setup, as that's the default port used by PostgreSQL.

      In the Maintenance database field, enter the name of the database you'd like to connect to. Note that this database must already be created on your server. Then, enter the PostgreSQL username and password you configured previously in the Username and Password fields, respectively.

      Create Server - Connection tab

      The empty fields in the other tabs are optional, and it's only necessary that you fill them in if you have a specific setup in mind in which they're required. Click the Save button, and the database will appear under the Servers in the Browser menu.

      You've successfully connected pgAdmin4 to your PostgreSQL database. You can do just about anything from the pgAdmin dashboard that you would from the PostgreSQL prompt. To illustrate this, we will create an example table and populate it with some sample data through the web interface.

      Step 6 — Creating a Table in the pgAdmin Dashboard

      From the pgAdmin dashboard, locate the Browser menu on the left-hand side of the window. Click on the plus sign (+) next to Servers (1) to expand the tree menu within it. Next, click the plus sign to the left of the server you added in the previous step (Sammy-server-1 in our example), then expand Databases, the name of the database you added (sammy, in our example), and then Schemas (1). You should see a tree menu like the following:

      Expanded Browser tree menu

      Right-click the Tables list item, then hover your cursor over Create and click Table….

      Create Table context menu

      This will open up a Create-Table window. Under the General tab of this window, enter a name for the table. This can be anything you'd like, but to keep things simple we'll refer to it as table-01.

      Create Table - General tab

      Then navigate to the Columns tab and click the + sign in the upper right corner of the window to add some columns. When adding a column, you're required to give it a Name and a Data type, and you may need to choose a Length if it's required by the data type you've selected.

      Additionally, the official PostgreSQL documentation states that adding a primary key to a table is usually best practice. A primary key is a constraint that indicates a specific column or set of columns that can be used as a special identifier for rows in the table. This isn't a requirement, but if you'd like to set one or more of your columns as the primary key, toggle the switch at the far right from No to Yes.

      Click the Save button to create the table.

      Create Table - Columns Tab with Primary Key turned on

      By this point, you've created a table and added a couple columns to it. However, the columns don't yet contain any data. To add data to your new table, right-click the name of the table in the Browser menu, hover your cursor over Scripts and click on INSERT Script.

      INSERT script context menu

      This will open a new panel on the dashboard. At the top you'll see a partially-completed INSERT statement, with the appropriate table and column names. Go ahead and replace the question marks (?) with some dummy data, being sure that the data you add aligns with the data types you selected for each column. Note that you can also add multiple rows of data by adding each row in a new set of parentheses, with each set of parentheses separated by a comma as shown in the following example.

      If you'd like, feel free to replace the partially-completed INSERT script with this example INSERT statement:

      INSERT INTO public."table-01"(
          col1, col2, col3)
          VALUES ('Juneau', 14, 337), ('Bismark', 90, 2334), ('Lansing', 51, 556);
      

      Example INSERT statement

      Click on the lightning bolt icon () to execute the INSERT statement. To view the table and all the data within it, right-click the name of your table in the Browser menu once again, hover your cursor over View/Edit Data, and select All Rows.

      View/Edit Data, All Rows context menu

      This will open another new panel, below which, in the lower panel's Data Output tab, you can view all the data held within that table.

      View Data - example data output

      With that, you've successfully created a table and populated it with some data through the pgAdmin web interface. Of course, this is just one method you can use to create a table through pgAdmin. For example, it's possible to create and populate a table using SQL instead of the GUI-based method described in this step.

      Conclusion

      In this guide, you learned how to install pgAdmin 4 from a Python virtual environment, configure it, serve it to the web with Apache, and how to connect it to a PostgreSQL database. Additionally, this guide went over one method that can be used to create and populate a table, but pgAdmin can be used for much more than just creating and editing tables.

      For more information on how to get the most out of all of pgAdmin's features, we encourage you to review the project's documentation. You can also learn more about PostgreSQL through our Community tutorials on the subject.



      Source link