Connection refused. AoF of Redis persistence (Append only File) and its summary; The difference between the RDB and aof persistence for Redis go The Redis Sort command; Docker+redis Persistent Configuration; Redis List-Rpoplpush; Redis solution (DENIED Redis is running in protected mode because Prote). Connect to the instance using SSH. Method 2: Run the AWSSupport-TroubleshootSSH automation document. AWSSupport-TroubleshootSSH automation document installs the Amazon EC2Rescue tool on the instance. Then this tool checks for and corrects some issues that cause remote connection errors when connecting to a Linux machine through SSH.
Because there are lots of different ways to configure redis, StackExchange.Redis offers a rich configuration model, which is invoked when calling Connect
(or ConnectAsync
):
The configuration
here can be either:
ConfigurationOptions
instancestring
representing the configurationThe latter is basically a tokenized form of the former.
The simplest configuration example is just the host name:
This will connect to a single server on the local machine using the default redis port (6379). Additional options are simply appended (comma-delimited). Ports are represented with a colon (:
) as is usual. Configuration options include an =
after the name. For example:
If you specify a serviceName in the connection string, it will trigger sentinel mode. This example will connect to a sentinel server on the local machineusing the default sentinel port (26379), discover the current master server for the mymaster
service and return a managed connectionpointing to that master server that will automatically be updated if the master changes:
An overview of mapping between the string
and ConfigurationOptions
representation is shown below, but you can switch between them trivially:
or:
A common usage is to store the basic details in a string, and then apply specific details at runtime:
Microsoft Azure Redis example with password
The ConfigurationOptions
object has a wide range of properties, all of which are fully documented in intellisense. Some of the more common options to use include:
Configuration string | ConfigurationOptions | Default | Meaning |
---|---|---|---|
abortConnect={bool} | AbortOnConnectFail | true (false on Azure) | If true, Connect will not create a connection while no servers are available |
allowAdmin={bool} | AllowAdmin | false | Enables a range of commands that are considered risky |
channelPrefix={string} | ChannelPrefix | null | Optional channel prefix for all pub/sub operations |
checkCertificateRevocation={bool} | CheckCertificateRevocation | true | A Boolean value that specifies whether the certificate revocation list is checked during authentication. |
connectRetry={int} | ConnectRetry | 3 | The number of times to repeat connect attempts during initial Connect |
connectTimeout={int} | ConnectTimeout | 5000 | Timeout (ms) for connect operations |
configChannel={string} | ConfigurationChannel | __Booksleeve_MasterChanged | Broadcast channel name for communicating configuration changes |
configCheckSeconds={int} | ConfigCheckSeconds | 60 | Time (seconds) to check configuration. This serves as a keep-alive for interactive sockets, if it is supported. |
defaultDatabase={int} | DefaultDatabase | null | Default database index, from 0 to databases - 1 |
keepAlive={int} | KeepAlive | -1 | Time (seconds) at which to send a message to help keep sockets alive (60 sec default) |
name={string} | ClientName | null | Identification for the connection within redis |
password={string} | Password | null | Password for the redis server |
user={string} | User | null | User for the redis server (for use with ACLs on redis 6 and above) |
proxy={proxy type} | Proxy | Proxy.None | Type of proxy in use (if any); for example “twemproxy” |
resolveDns={bool} | ResolveDns | false | Specifies that DNS resolution should be explicit and eager, rather than implicit |
serviceName={string} | ServiceName | null | Used for connecting to a sentinel master service |
ssl={bool} | Ssl | false | Specifies that SSL encryption should be used |
sslHost={string} | SslHost | null | Enforces a particular SSL host identity on the server’s certificate |
sslProtocols={enum} | SslProtocols | null | Ssl/Tls versions supported when using an encrypted connection. Use ‘|’ to provide multiple values. |
syncTimeout={int} | SyncTimeout | 5000 | Time (ms) to allow for synchronous operations |
asyncTimeout={int} | AsyncTimeout | SyncTimeout | Time (ms) to allow for asynchronous operations |
tiebreaker={string} | TieBreaker | __Booksleeve_TieBreak | Key to use for selecting a server in an ambiguous master scenario |
version={string} | DefaultVersion | (3.0 in Azure, else 2.0 ) | Redis version level (useful when the server does not make this available) |
CheckCertificateRevocation | true | A Boolean value that specifies whether the certificate revocation list is checked during authentication. |
Additional code-only options:
IReconnectRetryPolicy
) - Default: ReconnectRetryPolicy = LinearRetry(ConnectTimeout);
Tokens in the configuration string are comma-separated; any without an =
sign are assumed to be redis server endpoints. Endpoints without an explicit port will use 6379 if ssl is not enabled, and 6380 if ssl is enabled.Tokens starting with $
are taken to represent command maps, for example: $config=cfg
.
These options are parsed in connection strings for backwards compatibility (meaning they do not error as invalid), but no longer have any effect.
Configuration string | ConfigurationOptions | Previous Default | Previous Meaning |
---|---|---|---|
responseTimeout={int} | ResponseTimeout | SyncTimeout | Time (ms) to decide whether the socket is unhealthy |
writeBuffer={int} | WriteBuffer | 4096 | Size of the output buffer |
In many common scenarios, StackExchange.Redis will automatically configure a lot of settings, including the server type and version, connection timeouts, and master/replica relationships. Sometimes, though, the commands for this have been disabled on the redis server. In this case, it is useful to provide more information:
Which is equivalent to the command string:
Renaming Commands—
A slightly unusual feature of redis is that you can disable and/or rename individual commands. As per the previous example, this is done via the CommandMap
, but instead of passing a HashSet<string>
to Create()
(to indicate the available or unavailable commands), you pass a Dictionary<string,string>
. All commands not mentioned in the dictionary are assumed to be enabled and not renamed. A null
or blank value records that the command is disabled. For example:
The above is equivalent to (in the connection string):
Twemproxy is a tool that allows multiple redis instances to be used as though it were a single server, with inbuilt sharding and fault tolerance (much like redis cluster, but implemented separately). The feature-set available to Twemproxy is reduced. To avoid having to configure this manually, the Proxy
option can be used:
Normally StackExchange.Redis will resolve master/replica nodes automatically. However, if you are not using a management tool such as redis-sentinel or redis cluster, there is a chance that occasionally you will get multiple master nodes (for example, while resetting a node for maintenance it may reappear on the network as a master). To help with this, StackExchange.Redis can use the notion of a tie-breaker - which is only used when multiple masters are detected (not including redis cluster, where multiple masters are expected). For compatibility with BookSleeve, this defaults to the key named '__Booksleeve_TieBreak'
(always in database 0). This is used as a crude voting mechanism to help determine the preferred master, so that work is routed correctly.
Likewise, when the configuration is changed (especially the master/replica configuration), it will be important for connected instances to make themselves aware of the new situation (via INFO
, CONFIG
, etc - where available). StackExchange.Redis does this by automatically subscribing to a pub/sub channel upon which such notifications may be sent. For similar reasons, this defaults to '__Booksleeve_MasterChanged'
.
Both options can be customized or disabled (set to '
), via the .ConfigurationChannel
and .TieBreaker
configuration properties.
These settings are also used by the IServer.MakeMaster()
method, which can set the tie-breaker in the database and broadcast the configuration change message. The configuration message can also be used separately to master/replica changes simply to request all nodes to refresh their configurations, via the ConnectionMultiplexer.PublishReconfigure
method.
StackExchange.Redis automatically tries to reconnect in the background when the connection is lost for any reason. It keeps retrying until the connection has been restored. It would use ReconnectRetryPolicy to decide how long it should wait between the retries.ReconnectRetryPolicy can be linear (default), exponential or a custom retry policy.
Examples:
I'm receiving 'Connection refused' or 'Connection timed out' errors when trying to connect to my Amazon Elastic Compute Cloud (Amazon EC2) instance using SSH. How do I resolve this?
Error message: 'Error connecting to [instance], reason: Connection timed out: connect' refers to issues with connectivity to the instance, meaning the request fails to reach the instance and times out. This might happen if SSH isn't running on the instance or if a firewall is blocking access.
Error message: 'ssh: connect to host ec2-X-X-X-X.compute-1.amazonaws.com port 22: Connection refused' indicates that the instance refused the connection or the SSH service daemon isn't running. This error might also occur if a firewall is rejecting access to the instance.
Verify that there isn't a firewall blocking the connection, that the SSH service is running on the instance, and that SSH tcp port 22 is in the listening state.
There are three methods for performing these tasks:
Method 1: Use AWS Systems Manager Session Manager
Note: Installation of the SSM Agent is required to use this method. For more information on Session Manager and a complete list of prerequisites, see Setting up Session Manager.
1. Open the AWS Systems Manager console.
2. Start a session.
3. To disable firewalls and restart the SSH service, run the following commands.
Note: The preceding command flushes all main iptables rules, not just for port 22. After you regain access to your instance, review your firewall configuration (for example, ufw, firewalld, iptables).
4. Verify that the SSH tcp port (22) is in a listening state.
5. Terminate the session.
6. Connect to the instance using SSH.
Method 2: Run the AWSSupport-TroubleshootSSH automation document
AWSSupport-TroubleshootSSH automation document installs the Amazon EC2Rescue tool on the instance. Then this tool checks for and corrects some issues that cause remote connection errors when connecting to a Linux machine through SSH. For more information, see How can I use the AWSSupport-TroubleshootSSH Automation workflow to troubleshoot SSH connection issues?
Method 3: Use a user data script
Important
1. View the EC2 instance console logs. The following entry appears in the EC2 instance console logs if ufw is enabled.
2. Open the Amazon EC2 console.
3. Choose Instances from the navigation pane, and then select the instance you're trying to connect to.
4. Stop the instance.
5. Choose Actions, Instance Settings, View/Change User Data.
6. Copy the following user data script into the View/Change User Data dialog box, and then choose Save.
Note: The preceding command flushes all main iptables rules, not just for port 22. After you regain access to the instance, review your firewall configuration (for example, ufw, firewalld, iptables).
7. Connect to the instance using SSH.
8. The preceding user data script is set to run on every reboot of the instance. After regaining access to your instance, remove the user data script.
To remove user data:
1. Complete steps 1–4 in the Method 3: Use a user data script section.
2. Delete the user data script in the View/Change User Data dialogue box.