RabbitMQ in Docker

As part of a series of posts on running some core types of applications in Docker, its time to run up a message queue. Let’s try the Docker RabbitMQ container.

To run, simply use the following

docker run -d --hostname my-rabbit --name some-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3

If you’d like to use the RabbitMQ management tool, then run this instead (which runs RabbitMQ and the management tool)

docker run -d --hostname my-rabbit --name some-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3-management

Note: default login for the management UI is via a web browser using http://host:15672 obviously replacing the host with your server IP address. The default login and password are guest/guest.

From Visual Studio, create two test applications, one for sending messages and the second for receiving messages (mine are both console application) and using NuGet, add RabbitMQ.Client to them both. I’m going to just duplicate the code from the RabbitMQ tutorial here. So the application for sending messages should look like this

static void Main(string[] args)
{
   var factory = new ConnectionFactory
   {
      HostName = "localhost",
      Port = AmqpTcpEndpoint.UseDefaultPort
   };
   using (var connection = factory.CreateConnection())
   {
      using (var channel = connection.CreateModel())
      {
         channel.QueueDeclare("hello", false, false, false, null);

         var message = "Hello World!";
         var body = Encoding.UTF8.GetBytes(message);

         channel.BasicPublish(String.Empty, "hello", null,body);
         Console.WriteLine(" [x] Sent {0}", message);
      }
   }
   Console.ReadLine();
}

The receiver code looks like this

static void Main(string[] args)
{
   var factory = new ConnectionFactory
   {
      HostName = "localhost",
      Port = AmqpTcpEndpoint.UseDefaultPort
   };
   using (var connection = factory.CreateConnection())
   {
      using (var channel = connection.CreateModel())
      {
         channel.QueueDeclare("hello", false, false, false,null);

         var consumer = new EventingBasicConsumer(channel);
         consumer.Received += (model, ea) =>
         {
            var body = ea.Body;
            var message = Encoding.UTF8.GetString(body);
            Console.WriteLine(" [x] Received {0}", message);
         };
         channel.BasicConsume("hello", true, consumer);

         Console.WriteLine("Press [enter] to exit.");
         Console.ReadLine();
      }
   }
}

Obviously localhost should be replaced with the host name/ip address of the Docker server running RabbitMQ.