Skip to content

Instantly share code, notes, and snippets.

@zgulde
Last active December 4, 2017 18:09
Show Gist options
  • Save zgulde/cde1d049fe681a4384cfbb36bf6844d6 to your computer and use it in GitHub Desktop.
Save zgulde/cde1d049fe681a4384cfbb36bf6844d6 to your computer and use it in GitHub Desktop.

Setting up websockets in production

If you have a spring boot application that is using websockets, and you have a site deployed with the codeup tomcat setup, follow the instructions below:

Nginx Config

Add the following to the nginx config for your site in the location / block and restart nginx

...

location / {
    ...
    # add the three lines below
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

...

you can find the location of the nginx config file for your site by running:

./server site info example.com

Note that this is the location of the config file on your server, not on your local machine, so you'll need to login to the server and edit this file with admin privileges, then (again from the server) restart nginx.

For example:

# from your mac
./server login

then

# now that we are logged in to the server...

sudo nano /etc/nginx/sites-available/example.com
# make the changes, save and exit

# restart nginx
sudo systemctl restart nginx

HTTPS

In addition, if you have https enabled for the site, you'll need to add a little configuration to your spring application.

  1. Add the following line to your application.properties

    app.origin = http://localhost:8080
    

    Or

    app.origin = https://example.com
    

    The app.origin property's value should be the base url your site is served from.

    For your local application.properties, this should probably be http://localhost:8080.

    For the production application.properties, it should be your live domain, with the https prefix, for example: https://example.com

  2. In the WebSocketConfig class, register the value:

    // ...
    @Value("${app.origin}")
    private String origin;
    
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket")
            .setAllowedOrigins(origin)
            .withSockJS();
    }
    // ...

    Specifically, add the setAllowedOrigins method call and pass in the value from application.properties.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment