We develop a mathematical model to find the optimal inspection strategy for detecting a nuclear weapon (or nuclear material to make a weapon) from being smuggled into the United States in a shipping container, subject to constraints of port congestion and an overall budget. We consider an 11-layer security system consisting of shipper certification, container seals, and a targeting software system, followed by passive (neutron and gamma), active (gamma radiography), and manual testing at overseas and domestic ports. Currently implemented policies achieve a low detection probability, and improved security requires passive and active testing of trusted containers and manually opening containers that cannot be penetrated by radiography. The annual cost of achieving a high detection probability of a plutonium weapon using existing equipment in traditional ways is roughly several billion dollars if testing is done domestically, and is approximately five times higher if testing is performed overseas. Our results suggest that employing high-energy x-ray radiography and elongating the passive neutron tests at overseas ports may provide significant cost savings, and several developing technologies, radiation sensors inside containers and tamper-resistant electronic seals, should be pursued aggressively. Further effort is critically needed to develop a practical neutron interrogation scheme that reliably detects moderately shielded, highly enriched uranium.