One place for hosting & domains

      How To Expire Keys in Redis


      Introduction

      Redis is an open-source, in-memory key-value data store. Redis keys are persistent by default, meaning that the Redis server will continue to store them unless they are deleted manually. There may, however, be cases where you’ve set a key but you know you will want to delete it after a certain amount of time has passed; in other words, you want the key to be volatile. This tutorial explains how to set keys to expire, check the time remaining until a key’s expiration, and cancel a key’s expiration setting.

      How To Use This Guide
      This guide is written as a cheat sheet with self-contained examples. We encourage you to jump to any section that is relevant to the task you’re trying to complete.

      The commands shown in this guide were tested on an Ubuntu 18.04 server running Redis version 4.0.9. To set up a similar environment, you can follow Step 1 of our guide on How To Install and Secure Redis on Ubuntu 18.04. We will demonstrate how these commands behave by running them with redis-cli, the Redis command line interface. Note that if you’re using a different Redis interface — Redli, for example — the exact output of certain commands may differ.

      Alternatively, you could provision a managed Redis database instance to test these commands, but note that depending on the level of control allowed by your database provider, some commands in this guide may not work as described. To provision a DigitalOcean Managed Database, follow our Managed Databases product documentation. Then, you must either install Redli or set up a TLS tunnel in order to connect to the Managed Database over TLS.

      Setting Keys to Expire

      You can set an expiration time for an existing key with the expire command, which takes the name of the key and the number of seconds until expiration as arguments. To demonstrate this, run the following two commands. The first creates a string key named key_melon with a value of "cantaloupe", and the second sets it to expire after 450 seconds:

      • set key_melon "cantaloupe"
      • expire key_melon 450

      If the timeout was set successfully, the expire command will return (integer) 1. If setting the timeout failed, it will instead return (integer) 0.

      Alternatively, you can set the key to expire at a specific point in time with the expireat command. Instead of the number of seconds before expiration, it takes a Unix timestamp as an argument. A Unix timestamp is the number of seconds since the Unix epoch, or 00:00:00 UTC on January 1, 1970. There are a number of tools online you can use to find the Unix timestamp of a specific date and time, such as EpochConverter or UnixTimestamp.com.

      For example, to set key_melon to expire at 8:30pm GMT on May 1, 2025 (represented by the Unix timestamp 1746131400), you could use the following command:

      • expireat key_melon 1746131400

      Note that if the timestamp you pass to expireat has already occurred, it will delete the key immediately.

      Checking How Long Until a Key Expires

      Any time you set a key to expire, you can check the time remaining until expiry (in seconds) with ttl, which stands for “time to live”:

      Output

      (integer) 433

      For more granular information, you can run pttl which will instead return the amount of time until a key expires in milliseconds:

      Output

      (integer) 431506

      Both ttl and pttl will return (integer) -1 if the key hasn’t been set to expire and (integer) -2 if the key does not exist.

      Persisting Keys

      If a key has been set to expire, any command that overwrites the contents of a key — like set or getset — will clear a key’s timeout value. To manually clear a key’s timeout, use the persist command:

      The persist command will return (integer) 1 if it completed successfully, indicating that the key will no longer expire.

      Conclusion

      This guide details a number of commands used to manipulate and check key persistence in Redis. If there are other related commands, arguments, or procedures you’d like to see outlined in this guide, please ask or make suggestions in the comments below.

      For more information on Redis commands, see our tutorial series on How to Manage a Redis Database.



      Source link

      How To Manage Redis Databases and Keys


      Introduction

      Redis is an open-source, in-memory key-value data store. A key-value data store is a type of NoSQL database in which keys serve as unique identifiers for their associated values. Any given Redis instance includes a number of databases, each of which can hold many different keys of a variety of data types. In this tutorial, we will go over how to select a database, move keys between databases, and manage and delete keys.

      How To Use This Guide
      This guide is written as a cheat sheet with self-contained examples. We encourage you to jump to any section that is relevant to the task you’re trying to complete.

      The commands and outputs shown in this guide were tested on an Ubuntu 18.04 server running Redis version 4.0.9. To obtain a similar setup, you can follow Step 1 of our guide on How To Install and Secure Redis on Ubuntu 18.04. We will demonstrate how these commands behave by running them with redis-cli, the Redis command line interface. Note that if you’re using a different Redis interface — Redli, for example — the exact outputs of certain commands may differ.

      Alternatively, you could provision a managed Redis database instance to test these commands, but note that depending on the level of control allowed by your database provider, some commands in this guide may not work as described. To provision a DigitalOcean Managed Database, follow our Managed Databases product documentation. Then, you must either install Redli or set up a TLS tunnel in order to connect to the Managed Database over TLS.

      Managing Databases

      Out of the box, a Redis instance supports 16 logical databases. These databases are effectively siloed off from one another, and when you run a command in one database it doesn’t affect any of the data stored in other databases in your Redis instance.

      Redis databases are numbered from 0 to 15 and, by default, you connect to database 0 when you connect to your Redis instance. However, you can change the database you’re using with the select command after you connect:

      If you’ve selected a database other than 0, it will be reflected in the redis-cli prompt:

      To swap all the data held in one database with the data held in another, use the swapdb command. The following example will swap the data held in database 6 with that in database 8, and any clients connected to either database will be able to see changes immediately:

      swapdb will return OK if the swap is successful.

      If you want to move a key to a different Redis instance, you can run migrate. This command ensures the key exists on the target instance before deleting it from the source instance. When you run migrate, the command must include the following elements in this order:

      • The hostname or IP address of the destination database
      • The target database’s port number
      • The name of the key you want to migrate
      • The database number where you want to store the key on the destination instance
      • A timeout, in milliseconds, which defines the maximum amount of idle communication time between the two machines. Note that this isn’t a time limit for the operation, just that the operation should always make some level of progress within the defined length of time

      To illustrate:

      • migrate 203.0.113.0 6379 key_1 7 8000

      Additionally, migrate allows the following options which you can add after the timeout argument:

      • COPY: Specifies that the key should not be deleted from the source instance
      • REPLACE: Specifies that if the key already exists on the destination, the migrate operation should delete and replace it
      • KEYS: Instead of providing a specific key to migrate, you can enter an empty string ("") and then use the syntax from the keys command to migrate any key that matches a pattern. For more information on how keys works, see our tutorial on How To Troubleshoot Issues in Redis.

      Managing Keys

      There are a number of Redis commands that are useful for managing keys regardless of what type of data they hold. We’ll go over a few of these in this section.

      rename will rename the specified key. If it’s successful, it will return OK:

      You can use randomkey to return a random key from the currently selected database:

      Output

      "any_key"

      Use type to determine what type of data the given key holds. This command’s output can be either string, list, hash, set, zset, or stream:

      Output

      "string"

      If the specified key doesn’t exist, type will return none instead.

      You can move an individual key to another database in your Redis instance with the move command. move takes the name of a key and the database where you want to move the key as arguments. For example, to move the key key_1 to database 8, you would run the following:

      move will return OK if moving the key was successful.

      Deleting Keys

      To delete one or more keys of any data type, use the del command followed by one or more keys that you want to delete:

      If this command deletes the key(s) successfully it will return (integer) 1. Otherwise, it will return (integer) 0.

      The unlink command performs a similar function as del, with the difference being that del blocks the client as the server reclaims the memory taken up by the key. If the key being deleted is associated with a small object, the amount of time it takes for del to reclaim the memory is very small and the blocking time may not even be noticeable.

      However, it can become inconvenient if, for example, the key you’re deleting is associated with many objects, such as a hash with thousands or millions of fields. Deleting such a key can take a noticeably long time, and you’ll be blocked from performing any other operations until it’s fully removed from the server’s memory.

      unlink, however, first determines the cost of deallocating the memory taken up by the key. If it’s small then unlink functions the same way as del by the key immediately while also blocking the client. However, if there’s a high cost to deallocate memory for a key, unlink will delete the key asynchronously by creating another thread and incrementally reclaim memory in the background without blocking the client:

      Since it runs in the background, it’s generally recommended that you use unlink to remove keys from your server to reduce errors on your clients, though del will also suffice in many cases.

      Warning: The following two commands are considered dangerous. The flushdb and flushall commands will irreversibly delete all the keys in a single database and all the keys in every database on the Redis server, respectively. We recommend that you only run these commands if you are absolutely certain that you want to delete all the keys in your database or server.

      It may be in your interest to rename these commands to something with a lower likelihood of being run accidentally.

      To delete all the keys in the selected database, use the flushdb command:

      To delete all the keys in every database on a Redis server (including the currently selected database), run flushall:

      Both flushdb and flushall accept the async option, which allows you to delete all the keys on a single database or every database in the cluster asynchronously. This allows them to function similarly to the unlink command, and they will create a new thread to incrementally free up memory in the background.

      Backing Up Your Database

      To create a backup of the currently selected database, you can use the save command:

      This will export a snapshot of the current dataset as an .rdb file, which is a database dump file that holds the data in an internal, compressed serialization format.

      save runs synchronously and will block any other clients connected to the database. Hence, the save command documentation recommends that this command should almost never be run in a production environment. Instead, it suggests using the bgsave command. This tells Redis to fork the database: the parent will continue to serve clients while the child process saves the database before exiting:

      Note that if clients add or modify data while the bgsave operation is occurring, these changes won’t be captured in the snapshot.

      You can also edit the Redis configuration file to have Redis save a snapshot automatically (known as snapshotting or RDB mode) after a certain amount of time if a minimum number of changes were made to the database. This is known as a save point. The following save point settings are enabled by default in the redis.conf file:

      /etc/redis/redis.conf

      . . .
      save 900 1
      save 300 10
      save 60 10000
      . . .
      dbfilename "nextfile.rdb"
      . . .
      

      With these settings, Redis will export a snapshot of the database to the file defined by the dbfilename parameter every 900 seconds if at least 1 key is changed, every 300 seconds if at least 10 keys are changed, and every 60 seconds if at least 10000 keys are changed.

      You can use the shutdown command to back up your Redis data and then close your connection. This command will block every client connected to the database and then perform a save operation if at least one save point is configured, meaning that it will export the database in its current state to an .rdb file while preventing clients from making any changes.

      Additionally, the shutdown command will flush changes to Redis’s append-only file before quitting if append-only mode is enabled. The append-only file mode (AOF) involves creating a log of every write operation on the server in a file ending in .aof after every snapshot. AOF and RDB modes can be enabled on the same server, and using both persistence methods is an effective way to back up your data.

      In short, the shutdown command is essentially a blocking save command that also flushes all recent changes to the append-only file and closes the connection to the Redis instance:

      Warning: The shutdown command is considered dangerous. By blocking your Redis server’s clients, you can make your data unavailable to users and applications that depend on it. We recommend that you only run this command if you are testing out Redis’s behavior or you are absolutely certain that you want to block all your Redis server’s clients.

      In fact, it may be in your interest to rename this command to something with a lower likelihood of being run accidentally.

      If you’ve not configured any save points but still want Redis to perform a save operation, append the save option to the `shutdown command:

      If you have configured at least one save point but you want to shut down the Redis server without performing a save, you can add the nosave argument to the command:

      Note that the append-only file can grow to be very long over time, but you can configure Redis to rewrite the file based on certain variables by editing the redis.conf file. You can also instruct Redis to rewrite the append-only file by running the bgrewriteaof command:

      bgrewriteaof will create the shortest set of commands needed to bring the database back to its current state. As this command’s name implies, it will run in the background. However, if another persistence command is running in a background process already, that command must finish before Redis will execute bgrewriteaof.

      Conclusion

      This guide details a number of commands used to manage databases and keys. If there are other related commands, arguments, or procedures you’d like to see in this guide, please ask or make suggestions in the comments below.

      For more information on Redis commands, see our tutorial series on How to Manage a Redis Database.



      Source link

      How to Set Up SSH Keys on Debian 10


      Introduction

      SSH, or secure shell, is an encrypted protocol used to administer and communicate with servers. When working with a Debian server, chances are you will spend most of your time in a terminal session connected to your server through SSH.

      In this guide, we’ll focus on setting up SSH keys for a vanilla Debian 10 installation. SSH keys provide an easy, secure way of logging into your server and are recommended for all users.

      Step 1 — Create the RSA Key Pair

      The first step is to create a key pair on the client machine (usually your computer):

      By default ssh-keygen will create a 2048-bit RSA key pair, which is secure enough for most use cases (you may optionally pass in the -b 4096 flag to create a larger 4096-bit key).

      After entering the command, you should see the following output:

      Output

      Generating public/private rsa key pair. Enter file in which to save the key (/your_home/.ssh/id_rsa):

      Press enter to save the key pair into the .ssh/ subdirectory in your home directory, or specify an alternate path.

      If you had previously generated an SSH key pair, you may see the following prompt:

      Output

      /home/your_home/.ssh/id_rsa already exists. Overwrite (y/n)?

      Warning: If you choose to overwrite the key on disk, you will not be able to authenticate using the previous key anymore. Be very careful when selecting yes, as this is a destructive process that cannot be reversed.

      You should then see the following prompt:

      Output

      Enter passphrase (empty for no passphrase):

      Here you optionally may enter a secure passphrase, which is highly recommended. A passphrase adds an additional layer of security to prevent unauthorized users from logging in. To learn more about security, consult our tutorial on How To Configure SSH Key-Based Authentication on a Linux Server.

      You should then see the following output:

      Output

      Your identification has been saved in /your_home/.ssh/id_rsa. Your public key has been saved in /your_home/.ssh/id_rsa.pub. The key fingerprint is: a9:49:2e:2a:5e:33:3e:a9:de:4e:77:11:58:b6:90:26 username@remote_host The key's randomart image is: +--[ RSA 2048]----+ | ..o | | E o= . | | o. o | | .. | | ..S | | o o. | | =o.+. | |. =++.. | |o=++. | +-----------------+

      You now have a public and private key that you can use to authenticate. The next step is to place the public key on your server so that you can use SSH-key-based authentication to log in.

      Step 2 — Copy the Public Key to Debian Server

      The quickest way to copy your public key to the Debian host is to use a utility called ssh-copy-id. Due to its simplicity, this method is highly recommended if available. If you do not have ssh-copy-id available to you on your client machine, you may use one of the two alternate methods provided in this section (copying via password-based SSH, or manually copying the key).

      Copying Public Key Using ssh-copy-id

      The ssh-copy-id tool is included by default in many operating systems, so you may have it available on your local system. For this method to work, you must already have password-based SSH access to your server.

      To use the utility, you simply need to specify the remote host that you would like to connect to and the user account that you have password SSH access to. This is the account to which your public SSH key will be copied.

      The syntax is:

      • ssh-copy-id username@remote_host

      You may see the following message:

      Output

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      This means that your local computer does not recognize the remote host. This will happen the first time you connect to a new host. Type "yes" and press ENTER to continue.

      Next, the utility will scan your local account for the id_rsa.pub key that we created earlier. When it finds the key, it will prompt you for the password of the remote user's account:

      Output

      /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys username@203.0.113.1's password:

      Type in the password (your typing will not be displayed for security purposes) and press ENTER. The utility will connect to the account on the remote host using the password you provided. It will then copy the contents of your ~/.ssh/id_rsa.pub key into a file in the remote account's home ~/.ssh directory called authorized_keys.

      You should see the following output:

      Output

      Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'username@203.0.113.1'" and check to make sure that only the key(s) you wanted were added.

      At this point, your id_rsa.pub key has been uploaded to the remote account. You can continue on to Step 3.

      Copying Public Key Using SSH

      If you do not have ssh-copy-id available, but you have password-based SSH access to an account on your server, you can upload your keys using a conventional SSH method.

      We can do this by using the cat command to read the contents of the public SSH key on our local computer and piping that through an SSH connection to the remote server.

      On the other side, we can make sure that the ~/.ssh directory exists and has the correct permissions under the account we’re using.

      We can then output the content we piped over into a file called authorized_keys within this directory. We’ll use the >> redirect symbol to append the content instead of overwriting it. This will let us add keys without destroying previously added keys.

      The full command looks like this:

      • cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod -R go= ~/.ssh && cat >> ~/.ssh/authorized_keys"

      You may see the following message:

      Output

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      This means that your local computer does not recognize the remote host. This will happen the first time you connect to a new host. Type "yes" and press ENTER to continue.

      Afterwards, you should be prompted to enter the remote user account password:

      Output

      username@203.0.113.1's password:

      After entering your password, the content of your id_rsa.pub key will be copied to the end of the authorized_keys file of the remote user's account. Continue on to Step 3 if this was successful.

      Copying Public Key Manually

      If you do not have password-based SSH access to your server available, you will have to complete the above process manually.

      We will manually append the content of your id_rsa.pub file to the ~/.ssh/authorized_keys file on your remote machine.

      To display the content of your id_rsa.pub key, type this into your local computer:

      You will see the key's content, which should look something like this:

      Output

      ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCqql6MzstZYh1TmWWv11q5O3pISj2ZFl9HgH1JLknLLx44+tXfJ7mIrKNxOOwxIxvcBF8PXSYvobFYEZjGIVCEAjrUzLiIxbyCoxVyle7Q+bqgZ8SeeM8wzytsY+dVGcBxF6N4JS+zVk5eMcV385gG3Y6ON3EG112n6d+SMXY0OEBIcO6x+PnUSGHrSgpBgX7Ks1r7xqFa7heJLLt2wWwkARptX7udSq05paBhcpB0pHtA1Rfz3K2B+ZVIpSDfki9UVKzT8JUmwW6NNzSgxUfQHGwnW7kj4jp4AT0VZk3ADw497M2G/12N0PPB5CnhHf7ovgy6nL1ikrygTKRFmNZISvAcywB9GVqNAVE+ZHDSCuURNsAInVzgYo9xgJDW8wUw2o8U77+xiFxgI5QSZX3Iq7YLMgeksaO4rBJEa54k8m5wEiEE1nUhLuJ0X/vh2xPff6SQ1BL/zkOhvJCACK6Vb15mDOeCSq54Cr7kvS46itMosi/uS66+PujOO+xt/2FWYepz6ZlN70bRly57Q06J+ZJoc9FfBCbCyYH7U/ASsmY095ywPsBo1XQ9PqhnN1/YOorJ068foQDNVpm146mUpILVxmq41Cj55YKHEazXGsdBIbXWhcrRf4G2fJLRcGUr9q8/lERo9oxRm5JFX6TCmj6kmiFqv+Ow9gI0x8GvaQ== demo@test

      Access your remote host using whichever method you have available.

      Once you have access to your account on the remote server, you should make sure the ~/.ssh directory exists. This command will create the directory if necessary, or do nothing if it already exists:

      Now, you can create or modify the authorized_keys file within this directory. You can add the contents of your id_rsa.pub file to the end of the authorized_keys file, creating it if necessary, using this command:

      • echo public_key_string >> ~/.ssh/authorized_keys

      In the above command, substitute the public_key_string with the output from the cat ~/.ssh/id_rsa.pub command that you executed on your local system. It should start with ssh-rsa AAAA....

      Finally, we’ll ensure that the ~/.ssh directory and authorized_keys file have the appropriate permissions set:

      This recursively removes all “group” and “other” permissions for the ~/.ssh/ directory.

      If you’re using the root account to set up keys for a user account, it’s also important that the ~/.ssh directory belongs to the user and not to root:

      • chown -R sammy:sammy ~/.ssh

      In this tutorial our user is named sammy but you should substitute the appropriate username into the above command.

      We can now attempt passwordless authentication with our Debian server.

      Step 3 — Authenticate to Debian Server Using SSH Keys

      If you have successfully completed one of the procedures above, you should be able to log into the remote host without the remote account's password.

      The basic process is the same:

      If this is your first time connecting to this host (if you used the last method above), you may see something like this:

      Output

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      This means that your local computer does not recognize the remote host. Type "yes" and then press ENTER to continue.

      If you did not supply a passphrase for your private key, you will be logged in immediately. If you supplied a passphrase for the private key when you created the key, you will be prompted to enter it now (note that your keystrokes will not display in the terminal session for security). After authenticating, a new shell session should open for you with the configured account on the Debian server.

      If key-based authentication was successful, continue on to learn how to further secure your system by disabling password authentication.

      Step 4 — Disable Password Authentication on your Server

      If you were able to log into your account using SSH without a password, you have successfully configured SSH-key-based authentication to your account. However, your password-based authentication mechanism is still active, meaning that your server is still exposed to brute-force attacks.

      Before completing the steps in this section, make sure that you either have SSH-key-based authentication configured for the root account on this server, or preferably, that you have SSH-key-based authentication configured for a non-root account on this server with sudo privileges. This step will lock down password-based logins, so ensuring that you will still be able to get administrative access is crucial.

      Once you've confirmed that your remote account has administrative privileges, log into your remote server with SSH keys, either as root or with an account with sudo privileges. Then, open up the SSH daemon's configuration file:

      • sudo nano /etc/ssh/sshd_config

      Inside the file, search for a directive called PasswordAuthentication. This may be commented out. Uncomment the line and set the value to "no". This will disable your ability to log in via SSH using account passwords:

      /etc/ssh/sshd_config

      ...
      PasswordAuthentication no
      ...
      

      Save and close the file when you are finished by pressing CTRL + X, then Y to confirm saving the file, and finally ENTER to exit nano. To actually implement these changes, we need to restart the sshd service:

      • sudo systemctl restart ssh

      As a precaution, open up a new terminal window and test that the SSH service is functioning correctly before closing this session:

      Once you have verified your SSH service, you can safely close all current server sessions.

      The SSH daemon on your Debian server now only responds to SSH keys. Password-based authentication has successfully been disabled.

      Conclusion

      You should now have SSH-key-based authentication configured on your server, allowing you to sign in without providing an account password.

      If you'd like to learn more about working with SSH, take a look at our SSH Essentials Guide.



      Source link