以下安装步骤比官网更专业
我要强调说明一下baseurl=https://kong.bintray.com/kong-community-edition-rpm/centos/7
地址应该注意地方,参看下图说明:
[myth@contoso ~]$ su - password: 123 [root@contoso ~]# cat > /etc/yum.repos.d/kong-community-edition.repo [kong-community-edition] name=kong-community-edition baseurl=https://kong.bintray.com/kong-community-edition-rpm/centos/7 gpgcheck=0 repo_gpgcheck=0 enabled=1 [root@contoso ~]# exit [myth@contoso ~]$ sudo yum install epel-release [myth@contoso ~]$ sudo yum install kong-community-edition Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.vtti.vt.edu * epel: sjc.edge.kernel.org * extras: mirror.hackingand.coffee * ius: ftp.acc.umu.se * remi-php71: mirrors.ukfast.co.uk * remi-safe: mirrors.ukfast.co.uk * updates: centos.gbeservers.com Resolving Dependencies --> Running transaction check ---> Package kong-community-edition.noarch 0:0.13.1-1 will be installed --> Finished Dependency Resolution Dependencies Resolved ========================================================================================================= Package Arch Version Repository Size ========================================================================================================= Installing: kong-community-edition noarch 0.13.1-1 kong-community-edition 17 M Transaction Summary ========================================================================================================= Install 1 Package Total download size: 17 M Installed size: 45 M Is this ok [y/d/N]: y Downloading packages: kong-community-edition-0.13.1.el7.noarch.rpm | 17 MB 00:01:55 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : kong-community-edition-0.13.1-1.noarch 1/1 Verifying : kong-community-edition-0.13.1-1.noarch 1/1 Installed: kong-community-edition.noarch 0:0.13.1-1 Complete! [myth@contoso ~]$
https://www.postgresql.org/download/linux/redhat/
Install PostgreSQL Database
Install the repository RPM:
[root@contoso ~]# yum install https://download.postgresql.org/pub/repos/yum/10/redhat/rhel-7-x86_64/pgdg-centos10-10-2.noarch.rpm
Show auto-created the pgdg-10-centos.repo File content:
[root@contoso ~]# cat /etc/yum.repos.d/pgdg-10-centos.repo [pgdg10] name=PostgreSQL 10 $releasever - $basearch baseurl=https://download.postgresql.org/pub/repos/yum/10/redhat/rhel-$releasever-$basearch enabled=1 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-10 [pgdg10-source] name=PostgreSQL 10 $releasever - $basearch - Source failovermethod=priority baseurl=https://download.postgresql.org/pub/repos/yum/srpms/10/redhat/rhel-$releasever-$basearch enabled=0 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-10 [pgdg10-updates-testing] name=PostgreSQL 10 $releasever - $basearch baseurl=https://download.postgresql.org/pub/repos/yum/testing/10/redhat/rhel-$releasever-$basearch enabled=0 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-10 [pgdg10-source-updates-testing] name=PostgreSQL 10 $releasever - $basearch - Source failovermethod=priority baseurl=https://download.postgresql.org/pub/repos/yum/srpms/testing/10/redhat/rhel-$releasever-$basearch enabled=0 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-10Install the client packages:
[root@contoso ~]# yum install postgresql10
Install the server packages:
[root@contoso ~]# yum install postgresql10-server
Initialize the database and enable automatic start:
[root@contoso ~]# /usr/pgsql-10/bin/postgresql-10-setup initdb Initializing database ... OK
[root@contoso ~]# systemctl enable postgresql-10 [root@contoso ~]# systemctl start postgresql-10 [root@contoso ~]# systemctl status postgresql-10 鈼[0m postgresql-10.service - PostgreSQL 10 database server Loaded: loaded (/usr/lib/systemd/system/postgresql-10.service; enabled; vendor preset: disabled) Active: active (running) since Wed 2018-04-25 13:48:25 CST; 30s ago Docs: https://www.postgresql.org/docs/10/static/ Process: 3526 ExecStartPre=/usr/pgsql-10/bin/postgresql-10-check-db-dir ${PGDATA} (code=exited, status=0/SUCCESS) Main PID: 3536 (postmaster) CGroup: /system.slice/postgresql-10.service 鈹溾攢3536 /usr/pgsql-10/bin/postmaster -D /var/lib/pgsql/10/data/ 鈹溾攢3538 postgres: logger process 鈹溾攢3540 postgres: checkpointer process 鈹溾攢3541 postgres: writer process 鈹溾攢3542 postgres: wal writer process 鈹溾攢3543 postgres: autovacuum launcher process 鈹溾攢3544 postgres: stats collector process 鈹斺攢3545 postgres: bgworker: logical replication launcher Apr 25 13:48:25 contoso.org systemd[1]: Starting PostgreSQL 10 database server... Apr 25 13:48:25 contoso.org postmaster[3536]: 2018-04-25 13:48:25.263 CST [3536] LOG: listening on IPv6 address "::1", port 5432 Apr 25 13:48:25 contoso.org postmaster[3536]: 2018-04-25 13:48:25.263 CST [3536] LOG: listening on IPv4 address "127.0.0.1", port 5432 Apr 25 13:48:25 contoso.org postmaster[3536]: 2018-04-25 13:48:25.264 CST [3536] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" Apr 25 13:48:25 contoso.org postmaster[3536]: 2018-04-25 13:48:25.266 CST [3536] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432" Apr 25 13:48:25 contoso.org postmaster[3536]: 2018-04-25 13:48:25.273 CST [3536] LOG: redirecting log output to logging collector process Apr 25 13:48:25 contoso.org postmaster[3536]: 2018-04-25 13:48:25.273 CST [3536] HINT: Future log output will appear in directory "log". Apr 25 13:48:25 contoso.org systemd[1]: Started PostgreSQL 10 database server. [root@contoso ~]#[myth@contoso ~]$ sudo adduser kong # 新建一个Linux系统新用户 kong
[sudo] password for myth: 123
[myth@contoso ~]$ sudo su - postgres # 切换到postgres用户
-bash-4.2$ psql # 使用psql命令登录PostgreSQL控制台
psql (10.3)
Type "help" for help.
postgres=# \password postgres # 使用\password命令,为postgres用户设置一个密码
Enter new password: 123456
Enter it again: 123456
postgres=# CREATE USER kong WITH PASSWORD '123456'; # 创建数据库用户kong并设置密码
CREATE ROLE
postgres=# CREATE DATABASE kong OWNER kong; # 创建用户数据库kong并指定所有者为kong
CREATE DATABASE
postgres=# GRANT ALL PRIVILEGES ON DATABASE kong to kong; # 将kong数据库的所有权限都赋予kong,否则kong只能登录控制台,没有任何数据库操作权限。
GRANT
postgres=# \q # 使用\q命令退出控制台(也可以直接按ctrl+D)
-bash-4.2$ exit
logout
允许密码验证登录和远程连接:
vi /var/lib/pgsql/10/data/postgresql.conf
使用上面的命令行按 i 字母键进入编辑模式后找到
#listen_addresses = 'localhost' # what IP address(es) to listen on;
改成
listen_addresses = '*' # what IP address(es) to listen on;
按键盘Esc退出编辑模式,随后按键盘上的小写字母 wq 然后回车退出 vi 编辑命令,我们还需要改一个配置文件pg_hba.conf
[root@contoso ~]# cat > /var/lib/pgsql/10/data/pg_hba.conf # PostgreSQL Client Authentication Configuration File # =================================================== # # Refer to the "Client Authentication" section in the PostgreSQL # documentation for a complete description of this file. A short # synopsis follows. # # This file controls: which hosts are allowed to connect, how clients # are authenticated, which PostgreSQL user names they can use, which # databases they can access. Records take one of these forms: # # local DATABASE USER METHOD [OPTIONS] # host DATABASE USER ADDRESS METHOD [OPTIONS] # hostssl DATABASE USER ADDRESS METHOD [OPTIONS] # hostnossl DATABASE USER ADDRESS METHOD [OPTIONS] # # (The uppercase items must be replaced by actual values.) # # The first field is the connection type: "local" is a Unix-domain # socket, "host" is either a plain or SSL-encrypted TCP/IP socket, # "hostssl" is an SSL-encrypted TCP/IP socket, and "hostnossl" is a # plain TCP/IP socket. # # DATABASE can be "all", "sameuser", "samerole", "replication", a # database name, or a comma-separated list thereof. The "all" # keyword does not match "replication". Access to replication # must be enabled in a separate record (see example below). # # USER can be "all", a user name, a group name prefixed with "+", or a # comma-separated list thereof. In both the DATABASE and USER fields # you can also write a file name prefixed with "@" to include names # from a separate file. # # ADDRESS specifies the set of hosts the record matches. It can be a # host name, or it is made up of an IP address and a CIDR mask that is # an integer (between 0 and 32 (IPv4) or 128 (IPv6) inclusive) that # specifies the number of significant bits in the mask. A host name # that starts with a dot (.) matches a suffix of the actual host name. # Alternatively, you can write an IP address and netmask in separate # columns to specify the set of hosts. Instead of a CIDR-address, you # can write "samehost" to match any of the server's own IP addresses, # or "samenet" to match any address in any subnet that the server is # directly connected to. # # METHOD can be "trust", "reject", "md5", "password", "scram-sha-256", # "gss", "sspi", "ident", "peer", "pam", "ldap", "radius" or "cert". # Note that "password" sends passwords in clear text; "md5" or # "scram-sha-256" are preferred since they send encrypted passwords. # # OPTIONS are a set of options for the authentication in the format # NAME=VALUE. The available options depend on the different # authentication methods -- refer to the "Client Authentication" # section in the documentation for a list of which options are # available for which authentication methods. # # Database and user names containing spaces, commas, quotes and other # special characters must be quoted. Quoting one of the keywords # "all", "sameuser", "samerole" or "replication" makes the name lose # its special character, and just match a database or username with # that name. # # This file is read on server startup and when the server receives a # SIGHUP signal. If you edit the file on a running system, you have to # SIGHUP the server for the changes to take effect, run "pg_ctl reload", # or execute "SELECT pg_reload_conf()". # # Put your actual configuration here # ---------------------------------- # # If you want to allow non-local connections, you need to add more # "host" records. In that case you will also need to make PostgreSQL # listen on a non-local interface via the listen_addresses # configuration parameter, or via the -i or -h command line switches. # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all md5 # IPv4 local connections: host all all 127.0.0.1/32 md5 host all all 0.0.0.0/0 md5 # IPv6 local connections: host all all ::1/128 ident # Allow replication connections from localhost, by a user with the # replication privilege. local replication all md5 host replication all 127.0.0.1/32 ident host replication all ::1/128 ident
[root@contoso ~]# systemctl restart postgresql-10
使用密码登录看看:
[myth@contoso ~]$ sudo su - postgres [sudo] password for myth: 123 -bash-4.2$ psql -U kong -d kong -h 127.0.0.1 -p 5432 Password for user kong: 123456 psql (10.3) Type "help" for help. kong=> \l //\加上字母l,相当于mysql> show databases; List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+-------------+-------------+----------------------- kong | kong | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =Tc/kong + | | | | | kong=CTc/kong postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres (4 rows) kong=> \c kong //查看kong数据库登录用户名称 You are now connected to database "kong" as user "kong". kong=> \d //查看kong数据库所有表的名字 Did not find any relations.
日常可能还会用到的命令还有这些:
kong=> select pg_database_size('kong'); //查看kong数据库的大小,第2条SQL查看所有数据库的大小 kong=> select pg_database.datname, pg_database_size(pg_database.datname) AS size from pg_database; kong=> select pg_size_pretty(pg_database_size('kong')); //以KB,MB,GB的方式来查看数据库大小 kong=> \d test; //相当于mysql> desc test; kong=> select pg_relation_size('test'); //查看表大小 kong=> select pg_size_pretty(pg_relation_size('test')); //以KB,MB,GB的方式来查看表大小 kong=> select pg_size_pretty(pg_total_relation_size('test')); //查看表的总大小,包括索引大小 kong=> \di //相当于mysql> show index from test; kong=> select pg_size_pretty(pg_relation_size('test_id_pk')); //查看索大小 kong=> select spcname from pg_tablespace; //查看所有表空间 kong=> select pg_size_pretty(pg_tablespace_size('pg_default')); //查看表空间大小 如何查看PostgreSQL正在执行的SQL SELECT procpid, start, now() - start AS lap, current_query FROM (SELECT backendid, pg_stat_get_backend_pid(S.backendid) AS procpid, pg_stat_get_backend_activity_start(S.backendid) AS start, pg_stat_get_backend_activity(S.backendid) AS current_query FROM (SELECT pg_stat_get_backend_idset() AS backendid) AS S ) AS S WHERE current_query <> '<IDLE>' ORDER BY lap DESC; procpid:进程id start:进程开始时间 lap:经过时间 current_query:执行中的sql 怎样停止正在执行的sql SELECT pg_cancel_backend(进程id); 或者用系统函数 kill -9 进程id;
配置kong网关组件的默认配置文件kong.conf:
[root@contoso ~]# cp /etc/kong/kong.conf.default /etc/kong/kong.conf # 以模板配置文件生成默认的kong.conf文件
我们可以看看模板kong.conf.default配置文件都有那些内容:
[root@contoso ~]# cat /etc/kong/kong.conf.default # ----------------------- # Kong configuration file # ----------------------- # # The commented-out settings shown in this file represent the default values. # # This file is read when `kong start` or `kong prepare` are used. Kong # generates the Nginx configuration with the settings specified in this file. # # All environment variables prefixed with `KONG_` and capitalized will override # the settings specified in this file. # Example: # `log_level` setting -> `KONG_LOG_LEVEL` env variable # # Boolean values can be specified as `on`/`off` or `true`/`false`. # Lists must be specified as comma-separated strings. # # All comments in this file can be removed safely, including the # commented-out properties. # You can verify the integrity of your settings with `kong check <conf>`. #------------------------------------------------------------------------------ # GENERAL #------------------------------------------------------------------------------ #prefix = /usr/local/kong/ # Working directory. Equivalent to Nginx's # prefix path, containing temporary files # and logs. # Each Kong process must have a separate # working directory. #log_level = notice # Log level of the Nginx server. Logs are # found at <prefix>/logs/error.log. # Note: see http://nginx.org/en/docs/ngx_core_module.html#error_log for a list # of accepted values. #proxy_access_log = logs/access.log # Path for proxy port request access # logs. Set this value to `off` to # disable logging proxy requests. # If this value is a relative path, # it will be placed under the # `prefix` location. #proxy_error_log = logs/error.log # Path for proxy port request error # logs. Granularity of these logs is # adjusted by the `log_level` # directive. #admin_access_log = logs/admin_access.log # Path for Admin API request access # logs. Set this value to `off` to # disable logging Admin API requests. # If this value is a relative path, # it will be placed under the # `prefix` location. #admin_error_log = logs/error.log # Path for Admin API request error # logs. Granularity of these logs is # adjusted by the `log_level` # directive. #custom_plugins = # Comma-separated list of additional plugins # this node should load. # Use this property to load custom plugins # that are not bundled with Kong. # Plugins will be loaded from the # `kong.plugins.{name}.*` namespace. #anonymous_reports = on # Send anonymous usage data such as error # stack traces to help improve Kong. #------------------------------------------------------------------------------ # NGINX #------------------------------------------------------------------------------ #proxy_listen = 0.0.0.0:8000, 0.0.0.0:8443 ssl # Comma-separated list of addresses and ports on # which the proxy server should listen. # The proxy server is the public entrypoint of Kong, # which proxies traffic from your consumers to your # backend services. This value accepts IPv4, IPv6, and # hostnames. # Some suffixes can be specified for each pair: # - `ssl` will require that all connections made # through a particular address/port be made with TLS # enabled. # - `http2` will allow for clients to open HTTP/2 # connections to Kong's proxy server. # - Finally, `proxy_protocol` will enable usage of the # PROXY protocol for a given address/port. # # This value can be set to `off`, thus disabling # the proxy port for this node, enabling a # 'control-plane' mode (without traffic proxying # capabilities) which can configure a cluster of # nodes connected to the same database. # Note: see http://nginx.org/en/docs/http/ngx_http_core_module.html#listen for # a description of the accepted formats for this and other *_listen values. # Note bis: see https://www.nginx.com/resources/admin-guide/proxy-protocol/ # for more details about the `proxy_protocol` parameter. #admin_listen = 127.0.0.1:8001, 127.0.0.1:8444 ssl # Comma-separated list of addresses and ports on # which the Admin interface should listen. # The Admin interface is the API allowing you to # configure and manage Kong. # Access to this interface should be *restricted* # to Kong administrators *only*. This value accepts # IPv4, IPv6, and hostnames. # Some suffixes can be specified for each pair: # - `ssl` will require that all connections made # through a particular address/port be made with TLS # enabled. # - `http2` will allow for clients to open HTTP/2 # connections to Kong's proxy server. # - Finally, `proxy_protocol` will enable usage of the # PROXY protocol for a given address/port. # # This value can be set to `off`, thus disabling # the Admin interface for this node, enabling a # 'data-plane' mode (without configuration # capabilities) pulling its configuration changes # from the database. #nginx_user = nobody nobody # Defines user and group credentials used by # worker processes. If group is omitted, a # group whose name equals that of user is # used. Ex: [user] [group]. #nginx_worker_processes = auto # Determines the number of worker processes # spawned by Nginx. #nginx_daemon = on # Determines wether Nginx will run as a daemon # or as a foreground process. Mainly useful # for development or when running Kong inside # a Docker environment. #mem_cache_size = 128m # Size of the in-memory cache for database # entities. The accepted units are `k` and # `m`, with a minimum recommended value of # a few MBs. #ssl_cipher_suite = modern # Defines the TLS ciphers served by Nginx. # Accepted values are `modern`, # `intermediate`, `old`, or `custom`. # Note: see https://wiki.mozilla.org/Security/Server_Side_TLS for detailed # descriptions of each cipher suite. #ssl_ciphers = # Defines a custom list of TLS ciphers to be # served by Nginx. This list must conform to # the pattern defined by `openssl ciphers`. # This value is ignored if `ssl_cipher_suite` # is not `custom`. #ssl_cert = # The absolute path to the SSL certificate for # `proxy_listen` values with SSL enabled. #ssl_cert_key = # The absolute path to the SSL key for # `proxy_listen` values with SSL enabled. #client_ssl = off # Determines if Nginx should send client-side # SSL certificates when proxying requests. #client_ssl_cert = # If `client_ssl` is enabled, the absolute # path to the client SSL certificate for the # `proxy_ssl_certificate` directive. Note that # this value is statically defined on the # node, and currently cannot be configured on # a per-API basis. #client_ssl_cert_key = # If `client_ssl` is enabled, the absolute # path to the client SSL key for the # `proxy_ssl_certificate_key` address. Note # this value is statically defined on the # node, and currently cannot be configured on # a per-API basis. #admin_ssl_cert = # The absolute path to the SSL certificate for # `admin_listen` values with SSL enabled. #admin_ssl_cert_key = # The absolute path to the SSL key for # `admin_listen` values with SSL enabled. #upstream_keepalive = 60 # Sets the maximum number of idle keepalive # connections to upstream servers that are # preserved in the cache of each worker # process. When this number is exceeded, the # least recently used connections are closed. #server_tokens = on # Enables or disables emitting Kong version on # error pages and in the "Server" or "Via" # (in case the request was proxied) response # header field. #latency_tokens = on # Enables or disables emitting Kong latency # information in the "X-Kong-Proxy-Latency" # and "X-Kong-Upstream-Latency" response # header fields. #trusted_ips = # Defines trusted IP addresses blocks that are # known to send correct X-Forwarded-* headers. # Requests from trusted IPs make Kong forward # their X-Forwarded-* headers upstream. # Non-trusted requests make Kong insert its # own X-Forwarded-* headers. # # This property also sets the # `set_real_ip_from` directive(s) in the Nginx # configuration. It accepts the same type of # values (CIDR blocks) but as a # comma-separated list. # # To trust *all* /!\ IPs, set this value to # `0.0.0.0/0,::/0`. # # If the special value `unix:` is specified, # all UNIX-domain sockets will be trusted. # Note: see http://nginx.org/en/docs/http/ngx_http_realip_module.html for # examples of accepted values. #real_ip_header = X-Real-IP # Defines the request header field whose value # will be used to replace the client address. # This value sets the ngx_http_realip_module # directive of the same name in the Nginx # configuration. # If set to `proxy_protocol`, then at least # one of the `proxy_listen` entries must # have the `proxy_protocol` flag enabled. # Note: see http://nginx.org/en/docs/http/ngx_http_realip_module.html#real_ip_header # for a description of this directive. #real_ip_recursive = off # This value sets the ngx_http_realip_module # directive of the same name in the Nginx # configuration. # Note: see http://nginx.org/en/docs/http/ngx_http_realip_module.html#real_ip_recursive # for a description of this directive. #client_max_body_size = 0 # Defines the maximum request body size allowed # by requests proxied by Kong, specified in # the Content-Length request header. If a # request exceeds this limit, Kong will # respond with a 413 (Request Entity Too # Large). Setting this value to 0 disables # checking the request body size. # Note: see http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size # for further description of this parameter. Numeric values may be suffixed # with 'k' or 'm' to denote limits in terms of kilobytes or megabytes. #client_body_buffer_size = 8k # Defines the buffer size for reading the # request body. If the client request body is # larger than this value, the body will be # buffered to disk. Note that when the body is # buffered to disk Kong plugins that access or # manipulate the request body may not work, so # it is advisable to set this value as high as # possible (e.g., set it as high as # `client_max_body_size` to force request # bodies to be kept in memory). Do note that # high-concurrency environments will require # significant memory allocations to process # many concurrent large request bodies. # Note: see http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size # for further description of this parameter. Numeric values may be suffixed # with 'k' or 'm' to denote limits in terms of kilobytes or megabytes. #error_default_type = text/plain # Default MIME type to use when the request # `Accept` header is missing and Nginx # is returning an error for the request. # Accepted values are `text/plain`, # `text/html`, `application/json`, and # `application/xml`. #------------------------------------------------------------------------------ # DATASTORE #------------------------------------------------------------------------------ # Kong will store all of its data (such as APIs, consumers and plugins) in # either Cassandra or PostgreSQL. # # All Kong nodes belonging to the same cluster must connect themselves to the # same database. #database = postgres # Determines which of PostgreSQL or Cassandra # this node will use as its datastore. # Accepted values are `postgres` and # `cassandra`. #pg_host = 127.0.0.1 # The PostgreSQL host to connect to. #pg_port = 5432 # The port to connect to. #pg_user = kong # The username to authenticate if required. #pg_password = # The password to authenticate if required. #pg_database = kong # The database name to connect to. #pg_ssl = off # Toggles client-server TLS connections # between Kong and PostgreSQL. #pg_ssl_verify = off # Toggles server certificate verification if # `pg_ssl` is enabled. # See the `lua_ssl_trusted_certificate` # setting to specify a certificate authority. #cassandra_contact_points = 127.0.0.1 # A comma-separated list of contact # points to your cluster. #cassandra_port = 9042 # The port on which your nodes are listening # on. All your nodes and contact points must # listen on the same port. #cassandra_keyspace = kong # The keyspace to use in your cluster. #cassandra_timeout = 5000 # Defines the timeout (in ms), for reading # and writing. #cassandra_ssl = off # Toggles client-to-node TLS connections # between Kong and Cassandra. #cassandra_ssl_verify = off # Toggles server certificate verification if # `cassandra_ssl` is enabled. # See the `lua_ssl_trusted_certificate` # setting to specify a certificate authority. #cassandra_username = kong # Username when using the # `PasswordAuthenticator` scheme. #cassandra_password = # Password when using the # `PasswordAuthenticator` scheme. #cassandra_consistency = ONE # Consistency setting to use when reading/ # writing to the Cassandra cluster. #cassandra_lb_policy = RoundRobin # Load balancing policy to use when # distributing queries across your Cassandra # cluster. # Accepted values are `RoundRobin` and # `DCAwareRoundRobin`. # Prefer the later if and only if you are # using a multi-datacenter cluster. #cassandra_local_datacenter = # When using the `DCAwareRoundRobin` load # balancing policy, you must specify the name # of the local (closest) datacenter for this # Kong node. #cassandra_repl_strategy = SimpleStrategy # When migrating for the first time, # Kong will use this setting to # create your keyspace. # Accepted values are # `SimpleStrategy` and # `NetworkTopologyStrategy`. #cassandra_repl_factor = 1 # When migrating for the first time, Kong # will create the keyspace with this # replication factor when using the # `SimpleStrategy`. #cassandra_data_centers = dc1:2,dc2:3 # When migrating for the first time, # will use this setting when using the # `NetworkTopologyStrategy`. # The format is a comma-separated list # made of <dc_name>:<repl_factor>. #cassandra_schema_consensus_timeout = 10000 # Defines the timeout (in ms) for # the waiting period to reach a # schema consensus between your # Cassandra nodes. # This value is only used during # migrations. #------------------------------------------------------------------------------ # DATASTORE CACHE #------------------------------------------------------------------------------ # In order to avoid unecessary communication with the datastore, Kong caches # entities (such as APIs, Consumers, Credentials...) for a configurable period # of time. It also handles invalidations if such an entity is updated. # # This section allows for configuring the behavior of Kong regarding the # caching of such configuration entities. #db_update_frequency = 5 # Frequency (in seconds) at which to check for # updated entities with the datastore. # When a node creates, updates, or deletes an # entity via the Admin API, other nodes need # to wait for the next poll (configured by # this value) to eventually purge the old # cached entity and start using the new one. #db_update_propagation = 0 # Time (in seconds) taken for an entity in the # datastore to be propagated to replica nodes # of another datacenter. # When in a distributed environment such as # a multi-datacenter Cassandra cluster, this # value should be the maximum number of # seconds taken by Cassandra to propagate a # row to other datacenters. # When set, this property will increase the # time taken by Kong to propagate the change # of an entity. # Single-datacenter setups or PostgreSQL # servers should suffer no such delays, and # this value can be safely set to 0. #db_cache_ttl = 3600 # Time-to-live (in seconds) of an entity from # the datastore when cached by this node. # Database misses (no entity) are also cached # according to this setting. # If set to 0, such cached entities/misses # never expire. #------------------------------------------------------------------------------ # DNS RESOLVER #------------------------------------------------------------------------------ # By default the DNS resolver will use the standard configuration files # `/etc/hosts` and `/etc/resolv.conf`. The settings in the latter file will be # overridden by the environment variables `LOCALDOMAIN` and `RES_OPTIONS` if # they have been set. #dns_resolver = # Comma separated list of nameservers, each # entry in `ip[:port]` format to be used by # Kong. If not specified the nameservers in # the local `resolv.conf` file will be used. # Port defaults to 53 if omitted. Accepts # both IPv4 and IPv6 addresses. #dns_hostsfile = /etc/hosts # The hosts file to use. This file is read # once and its content is static in memory. # To read the file again after modifying it, # Kong must be reloaded. #dns_order = LAST,SRV,A,CNAME # The order in which to resolve different # record types. The `LAST` type means the # type of the last successful lookup (for the # specified name). The format is a (case # insensitive) comma separated list. #dns_stale_ttl = 4 # Defines, in seconds, how long a record will # remain in cache past its TTL. This value # will be used while the new DNS record is # fetched in the background. # Stale data will be used from expiry of a # record until either the refresh query # completes, or the `dns_stale_ttl` number of # seconds have passed. #dns_not_found_ttl = 30 # TTL in seconds for empty DNS responses and # "(3) name error" responses. #dns_error_ttl = 1 # TTL in seconds for error responses. #dns_no_sync = off # If enabled, then upon a cache-miss every # request will trigger its own dns query. # When disabled multiple requests for the # same name/type will be synchronised to a # single query. #------------------------------------------------------------------------------ # DEVELOPMENT & MISCELLANEOUS #------------------------------------------------------------------------------ # Additional settings inherited from lua-nginx-module allowing for more # flexibility and advanced usage. # # See the lua-nginx-module documentation for more informations: # https://github.com/openresty/lua-nginx-module #lua_ssl_trusted_certificate = # Absolute path to the certificate # authority file for Lua cosockets in PEM # format. This certificate will be the one # used for verifying Kong's database # connections, when `pg_ssl_verify` or # `cassandra_ssl_verify` are enabled. #lua_ssl_verify_depth = 1 # Sets the verification depth in the server # certificates chain used by Lua cosockets, # set by `lua_ssl_trusted_certificate`. # This includes the certificates configured # for Kong's database connections. #lua_package_path = # Sets the Lua module search path (LUA_PATH). # Useful when developing or using custom # plugins not stored in the default search # path. #lua_package_cpath = # Sets the Lua C module search path # (LUA_CPATH). #lua_socket_pool_size = 30 # Specifies the size limit for every cosocket # connection pool associated with every remote # server. [root@contoso ~]#
https://getkong.org/docs/0.13.x/configuration/
Please run `kong migrations up` to update/initialize the database schema. Be aware that Kong migrations should only run from a single node, and that nodes running migrations concurrently will conflict with each other and might corrupt your database schema!
[root@contoso ~]# kong migrations up migrating core for database kong core migrated up to: 2015-01-12-175310_skeleton core migrated up to: 2015-01-12-175310_init_schema core migrated up to: 2015-11-23-817313_nodes core migrated up to: 2016-02-29-142793_ttls core migrated up to: 2016-09-05-212515_retries core migrated up to: 2016-09-16-141423_upstreams core migrated up to: 2016-12-14-172100_move_ssl_certs_to_core core migrated up to: 2016-11-11-151900_new_apis_router_1 core migrated up to: 2016-11-11-151900_new_apis_router_2 core migrated up to: 2016-11-11-151900_new_apis_router_3 core migrated up to: 2016-01-25-103600_unique_custom_id core migrated up to: 2017-01-24-132600_upstream_timeouts core migrated up to: 2017-01-24-132600_upstream_timeouts_2 core migrated up to: 2017-03-27-132300_anonymous core migrated up to: 2017-04-18-153000_unique_plugins_id core migrated up to: 2017-04-18-153000_unique_plugins_id_2 core migrated up to: 2017-05-19-180200_cluster_events core migrated up to: 2017-05-19-173100_remove_nodes_table core migrated up to: 2017-06-16-283123_ttl_indexes core migrated up to: 2017-07-28-225000_balancer_orderlist_remove core migrated up to: 2017-10-02-173400_apis_created_at_ms_precision core migrated up to: 2017-11-07-192000_upstream_healthchecks core migrated up to: 2017-10-27-134100_consistent_hashing_1 core migrated up to: 2017-11-07-192100_upstream_healthchecks_2 core migrated up to: 2017-10-27-134100_consistent_hashing_2 core migrated up to: 2017-09-14-121200_routes_and_services core migrated up to: 2017-10-25-180700_plugins_routes_and_services migrating response-transformer for database kong response-transformer migrated up to: 2016-05-04-160000_resp_trans_schema_changes migrating ip-restriction for database kong ip-restriction migrated up to: 2016-05-24-remove-cache migrating statsd for database kong statsd migrated up to: 2017-06-09-160000_statsd_schema_changes migrating jwt for database kong jwt migrated up to: 2015-06-09-jwt-auth jwt migrated up to: 2016-03-07-jwt-alg jwt migrated up to: 2017-05-22-jwt_secret_not_unique jwt migrated up to: 2017-07-31-120200_jwt-auth_preflight_default jwt migrated up to: 2017-10-25-211200_jwt_cookie_names_default migrating cors for database kong cors migrated up to: 2017-03-14_multiple_orgins migrating basic-auth for database kong basic-auth migrated up to: 2015-08-03-132400_init_basicauth basic-auth migrated up to: 2017-01-25-180400_unique_username migrating key-auth for database kong key-auth migrated up to: 2015-07-31-172400_init_keyauth key-auth migrated up to: 2017-07-31-120200_key-auth_preflight_default migrating ldap-auth for database kong ldap-auth migrated up to: 2017-10-23-150900_header_type_default migrating hmac-auth for database kong hmac-auth migrated up to: 2015-09-16-132400_init_hmacauth hmac-auth migrated up to: 2017-06-21-132400_init_hmacauth migrating datadog for database kong datadog migrated up to: 2017-06-09-160000_datadog_schema_changes migrating tcp-log for database kong tcp-log migrated up to: 2017-12-13-120000_tcp-log_tls migrating acl for database kong acl migrated up to: 2015-08-25-841841_init_acl migrating response-ratelimiting for database kong response-ratelimiting migrated up to: 2015-08-03-132400_init_response_ratelimiting response-ratelimiting migrated up to: 2016-08-04-321512_response-rate-limiting_policies response-ratelimiting migrated up to: 2017-12-19-120000_add_route_and_service_id_to_response_ratelimiting migrating request-transformer for database kong request-transformer migrated up to: 2016-05-04-160000_req_trans_schema_changes migrating rate-limiting for database kong rate-limiting migrated up to: 2015-08-03-132400_init_ratelimiting rate-limiting migrated up to: 2016-07-25-471385_ratelimiting_policies rate-limiting migrated up to: 2017-11-30-120000_add_route_and_service_id migrating oauth2 for database kong oauth2 migrated up to: 2015-08-03-132400_init_oauth2 oauth2 migrated up to: 2016-07-15-oauth2_code_credential_id oauth2 migrated up to: 2016-12-22-283949_serialize_redirect_uri oauth2 migrated up to: 2016-09-19-oauth2_api_id oauth2 migrated up to: 2016-12-15-set_global_credentials oauth2 migrated up to: 2017-04-24-oauth2_client_secret_not_unique oauth2 migrated up to: 2017-10-19-set_auth_header_name_default oauth2 migrated up to: 2017-10-11-oauth2_new_refresh_token_ttl_config_value oauth2 migrated up to: 2018-01-09-oauth2_pg_add_service_id 62 migrations ran
[warn] ulimit is currently set to "1024". For better performance set it to at least "4096" using "ulimit -n"
[root@contoso ~]# ulimit -n 1024 [root@contoso ~]# cat >> /etc/security/limits.conf * soft nofile 65536 * hard nofile 65536 [root@contoso ~]# ulimit -n 65536 # 以上文件末尾追加两行参数值退出写入模式请按Ctrl + d [root@contoso ~]# ulimit -n 65536Start Kong
[root@contoso ~]# kong start Kong started
[root@contoso ~]# cat /var/lib/pgsql/10/data/postgresql.conf
Use Kong
curl -i http://localhost:8001 执行时会执行如下这条SQL语句:
SELECT (extract(epoch from created_at)*1000)::bigint as created_at, "config", "id", "name", "route_id", "enabled", "service_id", "api_id", "consumer_id" FROM plugins
[root@contoso ~]# curl -i http://localhost:8001/ HTTP/1.1 200 OK Date: Thu, 26 Apr 2018 03:06:17 GMT Content-Type: application/json; charset=utf-8 Transfer-Encoding: chunked Connection: keep-alive Access-Control-Allow-Origin: * Server: kong/0.13.1 {"plugins":{"enabled_in_cluster":[],"available_on_server":{"response-transformer":true,"correlation-id":true,"statsd":true,"jwt":true,"cors":true,"basic-auth":true,"key-auth":true,"ldap-auth":true,"http-log":true,"oauth2":true,"hmac-auth":true,"acl":true,"datadog":true,"tcp-log":true,"ip-restriction":true,"request-transformer":true,"file-log":true,"bot-detection":true,"loggly":true,"request-size-limiting":true,"syslog":true,"udp-log":true,"response-ratelimiting":true,"aws-lambda":true,"runscope":true,"rate-limiting":true,"request-termination":true}},"tagline":"Welcome to kong","configuration":{"error_default_type":"text\/plain","client_ssl":false,"lua_ssl_verify_depth":1,"trusted_ips":{},"prefix":"\/usr\/local\/kong","nginx_conf":"\/usr\/local\/kong\/nginx.conf","cassandra_username":"kong","admin_ssl_cert_csr_default":"\/usr\/local\/kong\/ssl\/admin-kong-default.csr","ssl_cert_key":"\/usr\/local\/kong\/ssl\/kong-default.key","admin_ssl_cert_key":"\/usr\/local\/kong\/ssl\/admin-kong-default.key","dns_resolver":{},"pg_user":"kong","mem_cache_size":"128m","ssl_ciphers":"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256","custom_plugins":{},"pg_host":"127.0.0.1","nginx_acc_logs":"\/usr\/local\/kong\/logs\/access.log","proxy_listen":["0.0.0.0:8000","0.0.0.0:8443 ssl"],"client_ssl_cert_default":"\/usr\/local\/kong\/ssl\/kong-default.crt","ssl_cert_csr_default":"\/usr\/local\/kong\/ssl\/kong-default.csr","db_update_frequency":5,"db_update_propagation":0,"nginx_err_logs":"\/usr\/local\/kong\/logs\/error.log","cassandra_port":9042,"dns_order":["LAST","SRV","A","CNAME"],"dns_error_ttl":1,"dns_stale_ttl":4,"nginx_optimizations":true,"database":"postgres","pg_database":"kong","nginx_worker_processes":"auto","lua_package_cpath":"","lua_package_path":".\/?.lua;.\/?\/init.lua;","nginx_pid":"\/usr\/local\/kong\/pids\/nginx.pid","upstream_keepalive":60,"admin_access_log":"logs\/admin_access.log","client_ssl_cert_csr_default":"\/usr\/local\/kong\/ssl\/kong-default.csr","proxy_listeners":[{"ssl":false,"ip":"0.0.0.0","proxy_protocol":false,"port":8000,"http2":false,"listener":"0.0.0.0:8000"},{"ssl":true,"ip":"0.0.0.0","proxy_protocol":false,"port":8443,"http2":false,"listener":"0.0.0.0:8443 ssl"}],"proxy_ssl_enabled":true,"pg_password":"******","lua_socket_pool_size":30,"server_tokens":true,"cassandra_ssl":false,"admin_ssl_enabled":true,"dns_no_sync":false,"cassandra_consistency":"ONE","db_cache_ttl":3600,"admin_error_log":"logs\/error.log","admin_ssl_cert_default":"\/usr\/local\/kong\/ssl\/admin-kong-default.crt","dns_not_found_ttl":30,"pg_ssl":false,"real_ip_header":"X-Real-IP","cassandra_data_centers":["dc1:2","dc2:3"],"cassandra_repl_strategy":"SimpleStrategy","latency_tokens":true,"cassandra_contact_points":["127.0.0.1"],"proxy_error_log":"logs\/error.log","admin_listen":["127.0.0.1:8001","127.0.0.1:8444 ssl"],"kong_env":"\/usr\/local\/kong\/.kong_env","cassandra_schema_consensus_timeout":10000,"dns_hostsfile":"\/etc\/hosts","log_level":"notice","client_max_body_size":"0","ssl_cert":"\/usr\/local\/kong\/ssl\/kong-default.crt","admin_ssl_cert":"\/usr\/local\/kong\/ssl\/admin-kong-default.crt","admin_ssl_cert_key_default":"\/usr\/local\/kong\/ssl\/admin-kong-default.key","cassandra_ssl_verify":false,"cassandra_lb_policy":"RoundRobin","ssl_cipher_suite":"modern","real_ip_recursive":"off","cassandra_repl_factor":1,"client_ssl_cert_key_default":"\/usr\/local\/kong\/ssl\/kong-default.key","nginx_daemon":"on","anonymous_reports":true,"proxy_access_log":"logs\/access.log","cassandra_timeout":5000,"pg_port":5432,"nginx_kong_conf":"\/usr\/local\/kong\/nginx-kong.conf","client_body_buffer_size":"8k","nginx_admin_acc_logs":"\/usr\/local\/kong\/logs\/admin_access.log","pg_ssl_verify":false,"admin_listeners":[{"ssl":false,"ip":"127.0.0.1","proxy_protocol":false,"port":8001,"http2":false,"listener":"127.0.0.1:8001"},{"ssl":true,"ip":"127.0.0.1","proxy_protocol":false,"port":8444,"http2":false,"listener":"127.0.0.1:8444 ssl"}],"cassandra_keyspace":"kong","ssl_cert_default":"\/usr\/local\/kong\/ssl\/kong-default.crt","ssl_cert_key_default":"\/usr\/local\/kong\/ssl\/kong-default.key","plugins":{"response-transformer":true,"correlation-id":true,"statsd":true,"jwt":true,"cors":true,"basic-auth":true,"key-auth":true,"ldap-auth":true,"http-log":true,"request-termination":true,"hmac-auth":true,"rate-limiting":true,"datadog":true,"tcp-log":true,"runscope":true,"aws-lambda":true,"response-ratelimiting":true,"acl":true,"loggly":true,"syslog":true,"request-size-limiting":true,"udp-log":true,"file-log":true,"request-transformer":true,"bot-detection":true,"ip-restriction":true,"oauth2":true}},"version":"0.13.1","node_id":"f10ee59e-7b78-45d3-8557-d78e0894d24f","lua_version":"LuaJIT 2.1.0-beta3","prng_seeds":{"pid: 12346":141527189168,"pid: 12347":116173139117,"pid: 12345":234993111247,"pid: 12344":199116552626},"timers":{"pending":5,"running":0},"hostname":"contoso.org"}
[root@contoso ~]# more /var/lib/pgsql/10/data/current_logfiles stderr log/postgresql-Thu.log [root@contoso ~]# tail -f /var/lib/pgsql/10/data/log/postgresql-Thu.log
[root@contoso ~]# pg_dump --help [root@contoso ~]# psql --help [root@contoso ~]# dropdb --help [root@contoso ~]# createdb --help [root@contoso ~]# pg_dump -h 127.0.0.1 -p 5432 -U postgres kong > /opt/kong-20180427.bak # 备份kong数据库 Password: 123456 [root@contoso ~]# kong stop # kong 服务必须先停止运行 [root@contoso ~]# dropdb -h 127.0.0.1 -p 5432 -U postgres kong # 删除kong数据库 Password: 123456 [root@contoso ~]# createdb -h 127.0.0.1 -p 5432 -U postgres kong # 创建kong数据库 Password: 123456 [root@contoso ~]# psql -h 127.0.0.1 -p 5432 -U postgres -d kong < /opt/kong-20180427.bak # 恢复kong数据库 Password for user postgres: 123456