We study the problem of a policymaker who aims at taming the spread of an epidemic while minimizing its associated social costs. The main feature of our model lies in the fact that the disease's transmission rate is a diffusive stochastic process whose trend can be adjusted via costly confinement policies. We provide a complete theoretical analysis, as well as numerical experiments illustrating the structure of the optimal lockdown policy. In all our experiments the latter is characterized by three distinct periods: the epidemic is first let freely evolve, then vigorously tamed, and finally a less stringent containment should be adopted. Moreover, the optimal containment policy is such that the product "reproduction number percentage of susceptible" is kept after a certain date strictly below the critical level of one, although the reproduction number is let oscillate above one in the last more relaxed phase of lockdown.